0

I am building a solar system app and I want to have all of my planet's info in a JSON file for easy access. The JSON file is in the following format
Planet-info.json, in the public folder of my React app

  "planets": [
        {
            "Name": "Mercury",
            "Description": "The smallest planet in our solar system and closest to the Sun—is only slightly larger than Earth's Moon. Mercury is the fastest planet, zipping around the Sun every 88 Earth days.",
            "Moons": 0,
            "Habititable": "false"
        },
        {
            "Name": "Venus",
            "Description": "is hot",
            "Moons": 0,
            "Habititable": "false"
        }
    ]

And I am fetching the data with the useEffect hook

 const [planetData, setPlanetData] = useState();
  useEffect(() => {
    const fetchData = () => {
      fetch("/planet-info.json").then((result) => {
        setPlanetData(result);
      });
    };
    fetchData();
    console.log(`planet data is ${planetData}`);
  }, []);

However when this code runs and the console.log statement runs it returns the line planet data is It does not say undefined, or even [Object object] it is simply blank and I am unable to troubleshoot from there.

1 Answer 1

1

fetchData runs asynchronously. So what's happening is

  1. fetchData starts
  2. console.log executes(before the json file has the chance to load)
  3. when the fetch completes, setPlanetData(result) happens. If you want to see the value printed out, this should do it:
useEffect(() => {
  fetch("/planet-info.json").then(result => {
    const json = result.json();
    console.log(json);
    setPlanetData(json);
  });
});
Sign up to request clarification or add additional context in comments.

5 Comments

TypeError: Cannot read property 'then' of undefined I think I am running the function in the wrong place.
Oops missed a line in my answer. I fixed it now. Needs a return in fetchData
It is no longer crashing, but now it is logging undefined
Lol look at me making mistakes. Fixed it now.
I made another update. Your JSON is probably fine. It's how fetch gets it back. You can use the json function on the response object to get the JSON value.

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.