To fetch data from an API in React, we can use the built-in fetch
function in JavaScript.
The fetch
function returns a Promise that resolves to the Response object representing the API's response. We can then use methods like json()
to convert the response data into a usable format.
Here's an example of how to fetch data from an API in React using fetch
and async/await
:
index.tsx529 chars25 lines
In this example, we use the useEffect
hook with an empty dependency array to run the fetchData
function only once when the component mounts. Inside the fetchData
function, we use await
to wait for the API response to complete before converting it to JSON format with response.json()
. Finally, we use the setData
function to update the state of the component with the fetched data.
Note that it's important to handle errors that may occur during the API fetch using a try-catch block or error handling functions.
gistlibby LogSnag