Fetching data from an API in JavaScript can be achieved using the fetch()
function, which is built-in to modern browsers. The fetch()
function returns a Promise, which we can use to handle the response received from the API.
Here's an example of how to use fetch()
to fetch data from an API:
index.tsx561 chars22 lines
In the code above, we first define the URL of the API we want to fetch data from. We then make a request to the API using fetch()
, which returns a Promise. We chain a series of then()
methods to the Promise to handle the response received from the API.
The first then()
method checks if the response received from the API is okay (i.e. the API returned a 200 OK
HTTP status code). If the response is okay, we parse the response data as JSON and return it. If the response is not okay, we throw an error.
The second then()
method receives the parsed JSON data and allows us to do something with it (e.g. display it on the page, manipulate it in some way, etc.).
Finally, we chain a catch()
method to the Promise to handle any errors that may have occurred during the fetch request.
Alternatively, we can use async/await
syntax to simplify the code:
index.tsx336 chars15 lines
In the code above, we define an async
function called fetchData()
which makes a request to the API using fetch()
and handles the response using await
and try/catch
syntax. We then call the fetchData()
function to initiate the fetch request.
gistlibby LogSnag