JS 009 — CRUD POST request

Greem
4 min readNov 19, 2023
  • Observe how to send a POST request using HTML forms and JavaScript
  • Explain the difference between optimistic and pessimistic rendering

slide: reveal .md

video: https://youtu.be/WCgaXe-b0YE

lectures: https://docs.google.com/spreadsheets/d/1gp4m4u5ke1_qVa-KU9P4XZTvQCy933wvfn4DwIKYREU/edit#gid=0

  1. Let’s code DRY (don’t repeat yourself)
//index.js
//line 61
////////////////////////////////////////////////////////////
// Invoking functions
//initial store render
//fetchResource('http://localhost:3000/stores/1') //get rid of this
fetchResource('/stores/1')
.then(store => {
renderHeader(store)
renderFooter(store)
})
.catch(e => console.error(e))

//render response data => books
//fetchResource('http://localhost:3000/books') //get rid of this
fetchResource('/books')
.then(books => books.forEach(renderBookCard))

//second .then returns JS data so we can send it to render function
.catch(e => console.error(e))

2. We can code more dynamically and add the url

line 3
////////////////////////////////////////////////////////////
// Fetch requests
// Function for making a GET request
//returns a promise
function fetchResource(url){
return fetch(`http://localhost:3000${url}`)
.then(res => res.json()) // the first .then returns a promise
}

Question: what does the first .then return?

answer: first .then returns a promise

Question: What do we do with the 2nd .then?

answer: second .then returns JS data so we can send it to render function

3. postBook function. What is this function returning?

answer: returns a promise

    //POST request 
function postBook(book){
return fetch("http://localhost:3000/books", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(book)
})
.then(res => res.json()) //1st then returns a promise
}

4. Then the rest of the asynchronous .then gets the promise and console log the response if it was successfully posted or not.

// Event Handlers
function handleForm(e){
e.preventDefault()
//Builds Book
const book = {
......
}
renderBookCard(book)

//after we create a new book object,
//we send the object to the server as a POST request
postBook(book) //postBook invocation which is the first .then returns a promise
.then(console.log) //2nd then console log the data
.catch(err => {
console.log(err)
removeBookCard(book)
})

}

5. For the user experience, how can we improve the fetch request? We are currently renderBookCard with the new book object before actually sending the POST fetch request.

4. We give useful immediate response to the users.

        //optimistic rendering
//renderBookCard(book)


//after we create a new book object, we send the object to the server as a POST request
//pessimistic rendering
postBook(book)
.then((book) => renderBookCard(book))
.catch(err => {
console.log(err)
removeBookCard(book)
})

}

5. optimistic rendering vs pessimistic rendering

Optimistic rendering: This occurs instantaneously and is confined to the DOM tree. It anticipates a successful response and renders the behavior based on the assumption of a successful outcome.

Pessimistic rendering: In this approach, the system sends the data via a fetch request and waits for the response, which can either be fulfilled or rejected. ‘Fulfilled’ indicates a successful post request, while ‘rejected’ indicates an error. Consequently, the data is rendered only after receiving confirmation of a fulfilled request.

6. What is different between GET request and POST request?

Post request has a second parameter (“initiator” object).

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options

7.

    //POST request 
function postBook(book){
return fetch("http://localhost:3000/books", { //init object
method: 'POST', //// *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json' //we are sending json object
},
body: JSON.stringify(book) //the body is book object,
//which turn that into json obj
})
.then(res => res.json())
}

8. Remember GET request and POST request are different

GET request: JSON object to JS object. parsing JSON obj into JS obj, using .json()

POST request: JS object to JSON object, using JSON.stringify(book)

9. Problem: How can we make the post fetch function more dynamic so in the future, when we want to post different kinds of data such as store, we can re-use the function?

10. Answer: With this new function, we take two parameter, url, and body object.

    function createResources(url, body){
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
.then(res => res.json())
}

11. When we invoke the fetch function with the first promise, we send two arguments, url and book object.

        createResources('http://localhost:3000/books', book)
//When we invoke the fetch function with the first promise,
//we send two arguments, url and book object.
.then(renderBookCard)
.catch(err => {
console.log(err)
removeBookCard(book)
})

--

--