When building a front end to an application one of the common needs is a way to communicate with a backend or API. Commonly used to retrieve data, a fetch is the current way to go about this.
The above image it a very basic/standard fetch. On the first line, the actual fetch method is taking in an argument (in this case we are accessing the ‘people’ page of a Star Wars API).
The second line is using ‘.then’ to basically use a promise which is essentially a place holder saying when the response comes back. The whole point of the asynchronous action of the fetch is that it can run other facets of the function while waiting for completion from certain tasks. Breaking up the linear top down nature of the function creates little gaps that lets the function run faster overall and more efficient. The second line here doesn't actually contain the response body so in order to get the JSON body content from the object, we have to use the .json() method. The .json() method, is a second promise that will be resolved when the response body is parsed as JSON.
The third line in the above example is another .then() method that is part of the asynchronous function. We are essentially waiting for the response body to be parsed as JSON and once that is done the third line is going to take that package and console log that data.
Fetching is such a common element in application building that they will become familiar fairly quickly. The asynchronous nature of the fetch() method makes it a fast and capable way to retrieve data. Fetching connects the front and backend of your application and allows quick, solid retrieval of your vital information.