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

Javascript JSON API fetch nested json

I have a nested json that I can obtain from the endpoint http://localhost:8080/salesmen/1
it looks like this

{
    "Id": 1,
    "name": "salesmen",
    "loc": "california",
    "inventory": [
        {
            "fruitId": 1,
            "Id": 1,
            "theDate": "08/12/2020",
            "descrip": "an apple",

        },
        {
            "fruitId": 2,
            "Id": 1,
            "theDate": "08/12/2021",
            "descrip": "a banana",

        }
    ]
}

I want to fetch the nested inventory part so I can build a table from it

I wrote a fetch that looks like this

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

When I inspect console all of the parameters in my fruitdata are undefined

Is this incorrect and do I need to do something else to obtain this?

useEffect(() => {
  fetch(SERVER_URL + "salesmen/1")
    .then((response) => response.json())
    .then((data) => {
      // fruits: responseData
      const fruitdata = [data].map((p) => {
        return {
          inventory: p.inventory,
          theDate: p.inventory.theDate,
          description: p.inventory.descrip,
        };

      });
      console.log(fruitdata)
      setfruits(fruitdata);
    })
    .catch((err) => console.error(err));
}, []);

>Solution :

useEffect(() => {
  fetch(SERVER_URL + "salesmen/1")
    .then((response) => response.json())
    .then((data) => {
      // fruits: responseData
      const fruitdata = data.inventory.map((p) => {  // mapping on invenroty will resolve the issue
        return {
          inventory: p.inventory,
          theDate: p.inventory.theDate,
          description: p.inventory.descrip,
        };

      });
      console.log(fruitdata)
     setfruits(fruitdata);

      
    })
    .catch((err) => console.error(err));
}, []);
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