javascriptreactjsjsonfetch

Data Fetching from a Static JSON File / REACT


I have a static json file appyling this format:

[
    {/*OBJECT1*/}, {/*OBJECT2*/} /* SO ON ... */
]

I wanted to fetch data to my React Component from this JSON file

I fetch the data in my React component by using following code

  useEffect(() => {
    async function getEssayData() {
      const res = await fetch('/essayData.json');
      const data = await res.json();
      return data;
    }

    const fetchData = getEssayData();
    console.log('Result Data   ' + fetchData);
    console.log(fetchData);
    console.log('Data    ' + data[0]);
  }, []);

i've tried lots of things, this is only one of them; however i couldn't reach my objects inside of JSON file.

(Fetching is happening correctly but i couldn't reach data objects ...)

console image , i really appreciate if you can help me with that.


Solution

  • When you try to log 'data' it is not defined there cause you created it inside a function (getEssayData). It is available only in that function. You shoul use useState to set the data which will be available anywhere in the component.

    
        const [data, setData] = useState(null);
    
      useEffect(() => {
        async function getEssayData() {
          const res = await fetch("/essayData.json");
          const data = await res.json();
          setData(data); // Save the fetched data in the state
        }
        getEssayData();
      }, []);
    
      // Log the fetched data when it is available
      useEffect(() => {
        if (data) {
          console.log("Fetched Data: ", data);
          console.log("First item: ", data[0]);
        }
      }, [data]);