-1

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.

3
  • I'm looking for an apt duplicate, but just move the console.log operations to inside the function. All the effect should be doing is calling the function, all of the logic in this case should be inside the getEssayData function. Commented Jan 20 at 17:13
  • @David YEAH IT WORKED THX but why, i was returning my data; and after returning, i was just logging it. (after edit => ) i got it, i figure it out i guess. thx again Commented Jan 20 at 17:17
  • 2
    Because you weren't awaiting the call to getEssayData(). It returns a Promise. Commented Jan 20 at 17:19

1 Answer 1

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.