Fetch at the Dog Park with JavaScript
Who Let the Dogs Out?! 🐶 🐶 🐶 🐶 🐶 🐶 🐶 🐶 🐶 🐶 🐶 🐶
The following blog will cover topics related to fetching data from an API. The aim is to discuss the basics of fetch and how promises are used in JavaScript to easily access data. Through a step-by-step example, we will become more familiar with using the fetch API to grab elements from an internal database server and manipulate the DOM using JavaScript.
Brief Overview of Fetch()
1.
fetch()
sends a request to a URL and a promise is returned as a response2. This promise is fulfilled when the server responds with a response object
3.
json()
is a response method that is invoked so that the response body can be read4. Another promise is returned with a resolve value as the body of the response.
Scenario: Who Let The Dogs Out?! Uh oh, the dog park gate was left open and now all of the dogs are running free. Help catch all the dogs and bring them back to the dog park where they can run around and play safely.
Deliverables:
- CREATE: Add a New Dog to the Playground
- READ: Fetch the Dogs & Add Dog Info to Each Dog Profile Card
- UPDATE: Update Info for Each Dog
- DELETE: Take Your Dog Home
The following HTML skeleton will be used for DOM manipulation:
Step 1: Create Your Server
- All of the dog data is stored in and can be retrieved from the db.json file
- You can access this data using a JSON server
- Run the following commands in your terminal to start your server
npm install -g json-server (if JSON server is not already installed)& then:json-server --watch db.json (provides us with a full fake REST API)
Step 2: Catch all the Dogs!
- Once our server is created it stores all of our dog data with restful routes at http://localhost:3000/dogs
- This is the URL that will be used to fetch all the dogs
- To easily access this URL when making fetch requests, we can assign it to a constant variable called dogURL.
const dogURL = `http://localhost:3000/dogs`
//GET Request to catch the dog
- Call the fetch function passing the URL of the API as a parameter
- The first response is a promise in the API language that needs to be translated to our front-end language. (In this case, we are converting JSON to JavaScript)
- Response instances are returned when fetch() promises are fulfilled
- Another promise is returned with the data we received from the response. (In this case, the data is an array of dogs so we use a
forEach()
to iterate over every dog)
Step 3: Add the Dog Info to the Dog Playground
- On the index.html page, there is a div with the id “dog-playground”
- To find the dog playground div, we can use the querySelector method
let dogPlayground = document.querySelector("#dog-playground")
- With the response data from our “GET” request to fetch all the dog objects, we will make a
<div class="card">
for each dog and add it to the dog-playground container
Each dog profile card should have the following child elements:
- h2 tag with the dog’s name
- image tag with the source of the dog’s image attribute
Step 4: Add a New Dog to the Park
How do we create a new dog instance and add it to the server?
- We need to find the location of where the dog data is being inputted
- Add an event listener to the form’s submit button
- Access the form in HTML file for submitting new dog data
- The values that get passed through the body of the post are the name and image associated with a new dog
Overview: When the user clicks on the “add new dog” button, a “POST” request is sent to add the dog to the dogPlayground collection
- The fetch request is given two arguments: dogURL and an object parameter
- The object specifies the method as “POST” and provides the appropriate headers and the JSONified data for the request
- The name and image is passed through the JSON body for the dog being created
- The internal server is updated with a new dog based on the information provided in the form.
- In the last
.then
method of our fetch, we call the catchDog function to display the new dog to the dogPlayground
Step 5: Update Info for Each Dog
- To update our dog data, we must fetch using dogURL for a specific dog ID
- “PATCH” request is sent and the updated dog data is appended to the dogPlayground by invoking the catchDog function
Step 6: Take Your Dog Home
- Must grab the specific dog object based on its ID
- Grab the dog along with its data from the HTML and delete from the backend with fetch and frontend with
dog.remove()
Yay! We were able to catch all the dogs using fetch! Now they can run around and play safely in the dog park or go home with their owners.
Conclusion: In this example, we manipulated the DOM using full CRUD (create, read, update, delete) operations.
I hope this brief overview was helpful in gaining a better understanding of how Fetch deals with requests and responses to access and manipulate data in JavaScript.
Thanks for reading!