fetching in react in javascript

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.tsx
import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://example.com/api/data');
      const json = await response.json();
      setData(json);
    }
    fetchData();
  }, []); // Fetch data only once when component mounted

  return (
    <div>
      {data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  );
}

export default MyComponent;
529 chars
25 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