1

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));
}, []);
1
  • 1
    Change [data] to data.inventory and there is no inventory in your inventory Commented Dec 11, 2021 at 6:51

1 Answer 1

1
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));
}, []);
Sign up to request clarification or add additional context in comments.

Comments

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.