Home > Software engineering >  Javascript JSON API fetch nested json
Javascript JSON API fetch nested json

Time:12-12

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

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));
}, []);

CodePudding user response:

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));
}, []);
  • Related