Home > other >  Fetching data in React's useEffect() returns error
Fetching data in React's useEffect() returns error

Time:10-11

i am tryin to display data like this :

    import React, {useEffect} from 'react'
    const Slider = ({ getData }) => {
        
    useEffect(() => {
       getData.map(item =>
         console.log("data : ", item)
       )
      }, []);
        
     return (
       <div className='slider__container'>
          // { listItems }  
       </div>
     )
   }
        
export default Slider

To see clear, here is my app.js where i called my component :

import React, { useState, useEffect } from 'react';
import Slider from './Slider';
import './App.css';

function App() {
  const [loadSlide, setLoadSlide] = useState(0);
  const [data, setData] = useState();
  const handleclick = () => {
    setLoadSlide(loadSlide   1)
  }

useEffect(() => {
    handleclick();
    fetch('/data.json')
    .then((response) => response.json())
    .then((json) =>  {
        setData(json.lvmh.slider)
        // console.log(json.lvmh.slider)
    });
}, [1]);

  return (
    <div className="App">
      <Slider title={`titre: ${loadSlide}`} getData={ data } />
    </div>
  );
}

export default App;

My json looks like this :

 "lvmh": {
      "slider": [
         {
            "id": 1,
            "progressBar": "01 / 07 Inspirationd",
            "title": "Are you looking for a perfume",
            "img": "https://wallpapercave.com/w/wp8671030",
            "slider": [
               { "type": "Woman" },
               { "type": "Mixte" }]
         },...

in the chrome console it shows Uncaught TypeError: Cannot read properties of undefined (reading 'map') and sometimes undefined

CodePudding user response:

Because data is never been defined.

CodePudding user response:

//check getData is an array
const getData = [1, 2, 3, 4, 5]
  if(Array.isArray(getData)) {
    getData.map(item => console.log(item))
}

CodePudding user response:

setState should be like this : useState([]);

import React, { useState, useEffect } from 'react';
    import Slider from './Slider';
    import './App.css';
    
    function App() {
      const [loadSlide, setLoadSlide] = useState(0);
      const [data, setData] = useState([]);
      const handleclick = () => {
        setLoadSlide(loadSlide   1)
      }
    
    useEffect(() => {
        handleclick();
        fetch('/data.json')
        .then((response) => response.json())
        .then((json) =>  {
            setData(json.lvmh.slider)
            // console.log(json.lvmh.slider)
        });
    }, [1]);
    
      return (
        <div className="App">
          <Slider title={`titre: ${loadSlide}`} getData={ data } />
        </div>
      );
    }
    
    export default App;
  • Related