Fetch API Data With Fetch() function and Axios

Fetch API Data With Fetch Function and Axios



Fetch()

Below code is to fetch the data from API using fetch function in React JS.

in the below example

fetching data from URL: https://jsonplaceholder.typicode.com/todos 

const [data,setData] useState([])
-- This data array is used to fill the data from API

useEffect() hook is used to fetch the data after page render
and it will store the data in data array

in return function using map function binding the list.

import React, { useEffect, useState } from "react";

const Display = (props) => {
  const [data, seData] = useState([]);

  // Fetch data from API using fetch function
  useEffect(()=>{
    fetch('https://jsonplaceholder.typicode.com/todos').then(
      response => response.json()
    ).then(json=> seData(json))
  },[])

  return (
    <div style={{margin:'20px'}}>
      {data.map(item=> <li key={item.id}>{item.title}</li>)}
    </div>
  );
};


export default Display;

Output:


Axios


import React, { useEffect, useState } from "react";
import axios from "axios";

const Display = (props) => {
  const [data, seteData] = useState([]);

  // Fetch data from API using axios.get
  useEffect(()=>{
    axios.get('https://jsonplaceholder.typicode.com/todos').then(
      response => seteData(response.data)
    )
  },[])

  return (
    <div style={{margin:'20px'}}>
      {data.map(item=> <li key={item.id}>{item.title}</li>)}
    </div>
  );
};


export default Display;



Raviteja Mulukuntla

Hello Viewers! My name is RaviTeja Mulukuntla and I am a senior software engineer working in a reputed IT firm. I like sharing my professional experience and knowledge skills with all users across all the Digital Platforms.

Previous Post Next Post

Contact Form