Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'response')

Getting an error while fetching data from an API the actual data I need is in response.
But when I try to access it just shows up as undefined. I added a loading function but that
does not seem to fix it.

Ex Json (The original is too big)

{
    "request": {
     
    },
    "response": [
      {
      Data I want here
       }

choose.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [data, setData] = useState();
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    setLoading(true);
    fetch(
  //example API key 
      "https://airlabs.co/api/v9/flights?api_key=2a6ae284-575d-41d8-948a-b789734174dd&arr_icao=VOBL"
    )

      .then((res) => res.json())
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

{data.response.map((post) => {

})

Full code link – https://codesandbox.io/s/heuristic-wood-meecre?file=/choose.js:2042-2072

>Solution :

You need to start with the loading state being true, because at the initial render you don’t yet have data.

Also move the rendering that you do inside the map into its own component, otherwise you get a runtime error about too many hooks:

{data.response.map((post) => (
        <Inner post={post} />
      ))}

(Here the component that renders each flight data is simply named "Inner")

You can see this sandbox for full demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading