MVC Architecture, REST on the Frontend and Promises
Model
maintains data used and manipulated by the app
persisted on the server between sessions
View
user interface, rendered from the model
provides affordances for user interaction
Controller
handles requests from the view, potentially updating the model
responsible for business logic; controls all changes to model
Client-Side Rendering
Model -> View -> Controller
needs to be in sync with server-side model
Used in place of a result that is not immediately available
Three states
Pending -> waiting
Fulfilled -> value is ready
Rejected -> some error
Actions when fulfilled or rejected
an alternative to callbacks
Basis of async/await in Javascript
const delay = 3000 ;
const cu_later =
new Promise ( ( resolve , reject ) => {
setTimeout ( ( ) => {
resolve ( 'Im back!' ) ;
} , delay ) ;
} ) ;
Promise constructor
new Promise(fn)
does nothing until the promise is used
Handler Function
fn(resolve, reject) => { ... }
Call resolve(value)
when value is ready (computed)
Call reject(error)
if there is a problem
.then(action)
runs action(value)
when promise is fulfilled
allows for chaining of promises
resolved only when action runs
resolves to return value of action
.catch(action)
runs handler(error)
when promise is rejected or on JS error
catches any exception or rejection in a chain
Handler function only runs once
Example:
getData ( ) // returns promise
. then ( ( res ) => {
if ( res . status != 200 )
throw new Error ( "No Data!" ) ;
return res . json ( ) ;
} )
. then ( ( json ) => setData ( json ) )
. catch ( ( error ) => {
console . log ( error ) ;
} ) ;
fetch(url, [, options])
makes an HTTP request
default method is GET
returns a promise in pending state
the promise is fulfilled when the client receives a response
Use JSON.stringify()
to convert an JS object to JSON format in body
Be sure to check res.status
in the response
should be 201 for a successful POST
used to attach state to a functional component
state can be mutated anywhere within the component function
passing a mutator through props to other functions lets them change the state too
state is initialized on first render
adding a side effect to any function component
use this to make an HTTP request to load data into state
function is called once on first render
with dependencies, it will turn when they change also