I couldn’t be more honest with you. I used to be terrified of doing fetches. Then there came the point of my life when I actually needed to use it. Just in case you’re like me, I’ll break it down in my simplest words.
What is Fetch?
Find a reliable API Endpoint
As a forewarning, I would strongly advise you not to use APIs that are deprecated, that hasn't been updated in years or that has very little and vague documentation. If the JSON data isn’t written in a way that makes sense to a non-programmer, then you may be spending a lot of time just trying to figure out where to expect to retrieve your data from in the response given back.
Just because you don't understand it doesn’t make you less of a skilled developer, there are such things as crappy API endpoints. If you’re having issues understanding how an API works, there are many developers on YouTube and other sites that break down the entire process on how to use it.
Testing the Endpoint
Not sure how many people actually do this but it helps me in great ways. The very first thing I do is to take the URL of the API I would like to use. I prefer to use the base URL than specific routes so I can be sure that the entire program works before trying to see if their other routes do. Here’s how I set mine up.
fetch('url').then(response => response.json()).then(data => console.log(data));
After doing this, I will be able to see the results in the developer console in my web browser. Now, the program is just waiting for me to handle the data. As you can see, the program returns a JSON object which will be used to display data to the front-end of an application. You would access this as you would a regular object.
For example, if we wanted to get the name of our Star Wars character, we would type in “data.name”. Sometimes you will find yourself dealing with an array of objects or an object filled with arrays. In that case, you will select the index with the information you’re looking for or write a function that will filter through all your received data and return the ones with the matching criteria.
This is only the basics. Fetch comes with a lot of features and some of them you will never even have to use. This tutorial is just to get you started with making your application. Read this to get a even deeper understanding of the logic behind Fetch.