Skip to content

How to fetch data from an api in React JS

React is the best way to develop a single-page web app and when it comes to fetching data from an API, It makes the data flow easier between components.

If you’re planning on making a web app using an API using ReactJS, Here is the piece of code you can use to do so.

To fetch data from an API in React, you can use the fetch() function, a built-in function for making HTTP requests. Here is an example of how you can use fetch() to get data from an API and set it in the state of your React component.

import React, { useState } from 'react';

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

  async function fetchData() {
    const response = await fetch('https://my-api.com/endpoint');
    const json = await response.json();
    setData(json);
  }

  return (
    <div>
      {data === null && <p>Loading data...</p>}
      {data !== null && (
        <div>
          <p>Data has been loaded!</p>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
JavaScript

In this example, the fetchData() function is used to fetch the data from the API. This function makes a request to the API endpoint using the fetch() function, and then it parses the response as JSON and sets the resulting data in the component’s state using the setData() function from the useState() hook.

When the component is rendered, it will display a loading message until the data is loaded, and then it will display the data in a formatted way.

Remember that this is just an example; you may need to modify it to fit your specific needs and requirements.

Learn how to create a react app on an android device.

Read react documentation about data fetching.

Subscribe to my newsletter for a such small valuable piece of useful information.