Home > OS >  TypeError: data.map is not a function Reactjs
TypeError: data.map is not a function Reactjs

Time:07-20

I am working with Reactjs,I am using nextjs,I am trying to get/fetch data via Api But i am getting following error

TypeError: data.map is not a function

Here is my code (component/Slider.js)

import React from 'react'
import { useState,useEffect } from 'react'
const Slider = () => {
 const [data,setData]=useState([]);
  useEffect(()=>{
        const getData =async() =>{
            const response =await fetch("http://localhost:1337/api/sliderinfos");
            const data = await response.json();
              setData(data);
        };
        getData();
  });
  
  return (
    <div className="main-banner header-text">
  
  {data.map((article) => (
      <li key={article.id}>{article.id}</li>
    ))}
    </div>
     )
    }
    
    export default Slider

Here is my json response
{"data":[{"id":1,"attributes":{"category":"FASHION","createdAt":"2022-07-19T04:52:38.578Z","updatedAt":"2022-07-19T04:52:40.001Z","publishedAt":"2022-07-19T04:52:39.996Z","title":"Morbi Dapibus Condimentum","createdby":"Admin","description":"You can browse "}},{"id":2,"attributes":{"category":"NATURE","createdAt":"2022-07-19T05:07:59.368Z","updatedAt":"2022-07-19T05:08:00.606Z","publishedAt":"2022-07-19T05:08:00.603Z","title":"Donec Porttitor Augue At Velit","createdby":"Admin","description":"You can browse }}

CodePudding user response:

Initially data is an array:

const [data,setData]=useState([]);

But when you update it to your JSON response, it's an object:

setData(data);

Because your JSON response is an object:

{"data":[/*...*/]}

That object has a property which is an array. Did you mean to set the state to that property?:

setData(data.data);

CodePudding user response:

It seems you trying to map over data that is an object

    useEffect(()=>{
        const getData =async() =>{
            const response =await fetch("http://localhost:1337/api/sliderinfos");
            const data = await response.json();
              setData(data.data);
        };
        getData();
  });

Replace data by data.data to get your array in your state

  • Related