What is the point to know how to patch if ….. Nobody sees it…. We are not supposed to have a personal and unique relationship with our database right?
We as Web Developer (I meant Embryo Web Developer have to be precise — like very precise… to the comma), it has been reminded to me today and that’s my story…
Using ‘fetch’ to Update the DOM
To update the content of the Dom (Document-Object Model), a useful idea is to use the ‘fetch’ method. I will not take too much time to explain all concepts of fetching, I want in particular, to take a closer look at one of its functions that will be very (VERY) handy when your user will need to add/or modify some information that should persist in the front-end and the back-end, like a comment for example.
The core interrogations are :
- Which element do I need to locate in order to listen to it ?
- Which type of event am I listening to ?
- What type of data am I handling right ? (Object collection of arrays or an Array of Objects…)
- What should happened, WHERE should this be happening my friend!
- Use the method ‘PATCH’ which will update the back-end.
- ANDDDDDD well let the world know it has been updated, don’t forget to let know your user that you have taken in consideration is will! Or what is the point of udpadeting right? More precisely, how will I reflect the updated data on the DOM.
When you find THE Node: use document.querySelector which takes as argument a CSS Selector, better store it in a variable.
Which type of event am I listening to? Am I waiting for a click from the user? A form Submission? Page to be scrolled? A mouse-over? Once this is determined, select the element where the event is supposed to occur and store it in a variable.
We must remember that the EventListener takes a call-back function. We must be using the ‘fetch’ method with the ‘PATCH’.
Also, we always need to IDENTIFY what we need to update. Every object needs an ID to be rightly located.
It could be in a parent element, in a sibling one. It could also be none existent so we have to create it. I would recommend looking for the ID or creating it in the first place, just because there is always a need to identify a specific element for a specific update!
Using fetch with the PATCH method takes in two arguments:
The first argument is the URL of the server + an interpolation of the id (or the id given) which will be needed to reach the element to update.
The second argument is an object which stipulates, to use method “Patch”, “headers” which has itself an object with the “Content-type” and the body which contains the property to update with the new input we want to update in the database. The body has the ‘JSON.stringify()’.
To reflect this change on the DOM, we need to PERFORM twice the ‘.then’ function, the second .then() function will content another function that has the code which will UPDATE the DOM will the new value. And this will put it accessible to the world!