Home > Enterprise >  Fetching data from JSON file returning nothing
Fetching data from JSON file returning nothing

Time:01-09

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.

CodePudding user response:

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);
  });
});
  •  Tags:  
  • Related