JS 010 — CRUD Patch request

Greem
4 min readNov 19, 2023

Lecture Goals

  • Review how to send a PATCH request using HTML forms and JavaScript
  • Review how to send a DELETE request using HTML buttons and JavaScript
  • Explain the difference between optimistic and pessimistic rendering
  1. We start the server using json-server and add relative path depending on where your current directory is
$json-server --watch src/db.json

2. CRUD: Acronym for operating on stored data. For functions of persistent storage.

HTTP verbs: a protocol to exhibit features of a RESTful system.

SQL(Structured Query Language) manages relational database and performs various operations.

3. Create a new input element when the card gets rendered

//line40 
function renderBookCard(cardData) {
.................
.................
const pInventory = document.createElement('input')

-add the inventory number as the inventory value

//line 45
function renderBookCard(cardData) {
.........
pPrice.textContent = `$${cardData.price}`

pInventory.type = 'number' //new
pInventory.value = cardData.inventory //new

btn.textContent = 'Delete'

........

-append the pInventory element to the li , the book card

   //line 55
function renderBookCard(cardData) {
const li = document.createElement('li')
........
........
//Event Listeners
li.append(h3,pAuthor,pPrice, pInventory, img,btn) //append pInventory
}

4. write PATCH request, similar to POST request

    // Fetch requests 
//global scope
//PATCH request
function updateResources(url, body){ //1st arg: url, 2nd arg: body obj
return fetch(url,{
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then(res => res.json())
}

5. Add event handler when the inventory number changes

//renderBookCard function       
//line 65
function renderBookCard(cardData) {
const li = document.createElement('li')
............

//Event Listeners
btn.addEventListener('click',()=>li.remove())

//PATCH
pInventory.addEventListener("change", () => {
updateResources("http://localhost:3000/books/2", {name:"patch test2"})
})

6. PATCH vs. PUT

PATCH: modify the individual part of the object

PUT: re-place the entire object

7. PATCH

8. PUT

9. Why is `PATCH` better option than ‘PUT` option for us ?

We can only target ONE attribute, instead of providing the entire attributes with new attribute.

10. Now we need to derive the inventory value. How can we derive the value that’s being passed from the change? so we can fire up as the second argument?

Let’s use EVENT object to get the inventory number from the DOM

//line 65 
pInventory.addEventListener('change', (e) => {
console.log(e.target.value)
updateResources("http://localhost:3000/books/2"
, {inventory: e.target.value}) //2nd argument
})

11. Where can we derive that specific id number of that selected card?

What’s the given information that we have it in the same function? Can we find the card id in the same scope?

url: localhost:3000/books/:id
//line 65
console.log(cardData)

pInventory.addEventListener('change', (e) => {
updateResources(`http://localhost:3000/books/${cardData.id}`
, {inventory: e.target.value})
})

The URL we are using is specific and we are targeting the individual attribute using the PATCH request, not PUT request.

12. What’s lacking in our PATCH request?

1. missing error handling

2. Not working with the return response from the fetch request

13. why did we separate the concern for GET and POST request?

We wanted to re-use the function so we can dynamically invoke the fetch function.

14. So INSTEAD of doing this

        //PATCH
function updateResources(url, body){
return fetch(url,{
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then(res => res.json())
.then(data => console.log(data))
.catch(console.error)
}

15. We will add the 2nd .then() method after we invoke the `updateResources` function

//line 80      
function renderBookCard(cardData) {
const li = document.createElement('li')
............

//PATCH
pInventory.addEventListener('change', (e) => {
e.preventDefault()
updateResources(`http://localhost:3000/books/${cardData.id}`, {inventory: e.target.value})
.then(data => console.log(data))
.catch(console.error)
})

16. Finally, we can bring this function out to separate the concerns.

//line 80
//PATCH
pInventory.addEventListener('change', (e)=> handlePatch(e, cardData))

and create a new function

//line 119  
//PATCH
function handlePatch (e, cardData) {
e.preventDefault()
updateResources(`http://localhost:3000/books/${cardData.id}`, {inventory: e.target.value})
.then(data => console.log(data))
.catch(console.error)
}

https://vimeo.com/739756789 24:06

--

--