Haseeb.

The Best Way to Fetch Data in React and Next.js

January 15, 2024

The Best Way to Fetch Data in React and Next.js

Banner

In the world of web development, making HTTP requests is a fundamental task. Developers often face the choice of which library or tool to use for this purpose. In this article, we will compare three popular options for handling HTTP requests in TypeScript: fetch, axios, and tanstack react-query.

Fetch

Fetch is a built-in JavaScript method for making HTTP requests. It provides a simple and native way to send and receive data from a server. Here's how you can make a GET request using Fetch in TypeScript:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Fetch is built-in, so it is lightweight, but it does not handle caching and error states properly. When making a POST request, you have to pass headers and content types manually:

const url = 'https://api.example.com/postData';

const data = {
  key1: 'value1',
  key2: 'value2',
};

const requestOptions = {
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json',
  },
};

fetch(url, requestOptions)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

The syntax can be quite verbose and less intuitive compared to other libraries.

Axios

Axios is a popular JavaScript library for making HTTP requests. It simplifies the process of making requests and provides additional features, such as request and response interceptors. First, install it:

npm install axios

Here's how you can use axios to make a GET request:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));

For a POST request:

import axios from 'axios';

const url = 'https://api.example.com/postData';

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
};

const data = {
  key1: 'value1',
  key2: 'value2',
};

axios.post(url, data, { headers })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

Axios has a much cleaner syntax compared to fetch. However, it still requires manual management of loading and error states.

React Query

React Query is a powerful library designed specifically for handling data fetching and state management. It abstracts the complexities of data management, offering a highly efficient and developer-friendly experience. First, install it:

npm install @tanstack/react-query

Here's an example of using React Query to fetch data in a React component:

import { useQuery } from '@tanstack/react-query';

const MyComponent = () => {
  const { data, error, loading } = useQuery('data', () =>
    fetch('https://api.example.com/data').then(response => response.json())
  );

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

  return (
    <>
      {loading ? <Text>Loading...</Text> : <div>Data: {data}</div>}
    </>
  );
};

For post or mutation requests:

import { useMutation } from '@tanstack/react-query';
import axios from 'axios'

const PostData = () => {
  const postMutation = useMutation((newData) =>
     axios.post("url")
    }).then((response) => response.json())
  );

  const handlePost = async () => {
    const newData = {
      key1: 'value1',
      key2: 'value2',
    };

    await postMutation.mutateAsync(newData);
  };

  return (
    <div>
      <button onClick={handlePost} disabled={postMutation.isLoading}>
        {postMutation.isLoading ? 'Posting...' : 'Post Data'}
      </button>

      {postMutation.isError && (
        <div>An error occurred: {postMutation.error.message}</div>
      )}

      {postMutation.isSuccess && (
        <div>Data Posted Successfully: {postMutation.data}</div>
      )}
    </div>
  );
};

React Query provides a beautiful way to handle different loading and error states. For further knowledge, visit their official documentation.