DEV Community

Cover image for Different Ways to fetch data from API in Reactjs
Kamran Ahmad
Kamran Ahmad

Posted on

Different Ways to fetch data from API in Reactjs

  1. Using the fetch() method:
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data))
  }, []);

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


Enter fullscreen mode Exit fullscreen mode
  1. Using the axios library:
import React, { useState, useEffect } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then(response => setData(response.data))
  }, []);

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


Enter fullscreen mode Exit fullscreen mode
  1. Using the async/await syntax:
import React, { useState, useEffect } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    async function fetchData() {
      const response = await axios.get('https://api.example.com/data');
      setData(response.data);
    }
    fetchData();
  }, []);

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


Enter fullscreen mode Exit fullscreen mode
  1. Using the swr library:
import React, { useState } from 'react';
import useSWR from 'swr';

function Example() {
  const { data, error } = useSWR('https://api.example.com/data');

  if (error) return <div>Failed to load data</div>;
  if (!data) return <div>Loading...</div>;

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

Enter fullscreen mode Exit fullscreen mode

Please note that in all the above examples, https://api.example.com/data should be replaced with the actual API endpoint you want to fetch data from.

  • Using the react-query library
  • Using the react-async library
  • Using a custom Hook and the useEffect Hook to handle the API call
  • Using a Higher-Order Component (HOC) to handle the API call
  • Using a Render Prop Component to handle the API call
  • Using the redux-thunk library to handle the API call in a Redux store.

Top comments (0)