Fetch Data in React JS in modern way

Fetch Data in React JS in modern way

There are several ways to fetch data in a React application. Here are some of the most common:

Fetch API :

The Fetch API is a built-in browser API for fetching resources, including data from a server. It returns a Promise that resolves to the response object. You can use the Fetch API in combination with React’s useEffect hook to fetch data and update the component state.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Data:</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

Axios:

Axios is a popular library for making HTTP requests from a browser or node.js. It returns a Promise that resolves to the response object. You can use Axios in combination with React’s useEffect hook to fetch data and update the component state.

import { useState, useEffect } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    axios.get('/api/data')
      .then(response => setData(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Data:</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

But what if I tell you about something crazy

Sure! Here is an example of how you can use React Query to fetch data from an API and display it in a React component:

First, you’ll need to install React Query using npm or yarn:

npm install react-query

Next, you can import the useQuery hook from React Query in your component:

import { useQuery } from 'react-query';

Then, you can use the useQuery hook to fetch data from an API. In this example, we’ll fetch a list of users from the JSONPlaceholder API:

function Users() {
  const { isLoading, error, data } = useQuery('users', () =>
    fetch('https://jsonplaceholder.typicode.com/users').then((res) =>
      res.json()
    )
  );

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {data.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Noticed this piece of code?

const { isLoading, error, data } = useQuery('users', () =>
  fetch('https://jsonplaceholder.typicode.com/users').then((res) =>
    res.json()
  )
);

The code is using object destructuring to extract these properties from the object returned by the useQuery hook and store them in variables with the same names (isLoading, error, and data).

The useQuery hook returns an object that contains three properties: isLoading, error, and data.

  • isLoading: A boolean that is true while the query is loading data from the API.

  • error: An object that contains any error that occurred while fetching the data. If there was no error, this will be null.

  • data: The data that was fetched from the API. If there was an error, this will be undefined.

Summary

Installing React Query can help developers streamline the process of fetching and managing remote data in their React applications, making it easier to build robust and scalable front-end experiences.

Did you find this article valuable?

Support Gujarati Coder by becoming a sponsor. Any amount is appreciated!