Axios not fetching data using Reactjs

Advertisements

I am working with Reactjs/nextjs and i am trying to fetch data using "Axios", In "Api url" data is fetching/showing but in my webpage showing "There are no records yet",Where i am wrong ? Here is my current code

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


function Displaydata() {
      const [posts,setPosts]=useState([]);

useEffect(()=>
{
    const getdata=async()=>
    {
        const { data: res } = await axios.get(
            "xxxxxxxxxxxxxxxxxxxx/api/Allvideo"
          );
          console.log(res);
          setPosts(res);
    };
})
return(
    <div>
        {posts?.length ? posts.map((product: { id: any; link: any; }) => <p key={product.id}>
        {product.id}-{product.link}</p>) 
            : <h3>There are no records yet</h3>}
            </div>
    )
}

export default Displaydata

>Solution :

We need to pass second argument for useEffect as empty array or array of values. and then getdata function declared but not called. please find the below code.

useEffect(() => { 
  const getdata = async() => {
    const { data: res } = await axios.get("xxxxxxxxxxxxxxxxxxxx/api/Allvideo");
      console.log(res);
      setPosts(res);
   };
   getdata();
 }, []);

hope this helps!!!

Leave a Reply Cancel reply