Home > Blockchain >  How to display fetched array of objects and save multiple fetched arrays to state?
How to display fetched array of objects and save multiple fetched arrays to state?

Time:06-13

If i try to display user.meniu.pret inside the map function it wont display anything. user.meniu[0].pret displays values but wont give me the final results i want

How can i fetch the data and display the values inside the response.menu ?

function App() {
  const [users, setUsers] = useState();
  const [meniu, setMeniu] = useState()

  const getApiData = async () => {
    const response = await fetch(
      "https://vercelfastfoodapi.vercel.app/fastfood/"
    ).then((response) => response.json());

    setUsers(response);

    setMeniu(response[1].meniu)  // <----------- SAVES VALUES
    setMeniu(response.meniu) // <------------ UNDEFINED

  };

  useEffect(() => {
    getApiData();
  }, []);

  return (
    <div className="App">

 {users &&
        users.map((user) => (
          <div className="item-container" key={user._id}>
            Id: <b> {user.restaurant} </b>  <br/>
            Restaurant: {user.meniu.pret} // <------- WONT DISPLAY ANYTHING. user.meniu[0].pret works fine

          </div>
        ))} 


          <button onClick={() => console.log(meniu)}>aaaa </button>
    </div>
  );
}

CodePudding user response:

user.meniu is an array not an object. This is the reason why user.meniu.pret gives you undefined while user.meniu[0].pret lets you access the property pret of the first object of the array user.meniu. Now, if you want to save all the fetched menius in the state you can do:

setMeniu(response.map(r => r.meniu)); // remember that the meniu state now will be an array of objects

Now, if you want to display all the pret values from each object of the array you can simply do:

<div className="item-container" key={user._id}>
 Id: <b> {user.restaurant} </b>  <br/>
 Restaurant: {meniu.map(m => m.priet)}
</div>

Or if you want to use the user object you can do:

<div className="item-container" key={user._id}>
 Id: <b> {user.restaurant} </b>  <br/>
 Restaurant: {user.meniu.map(m => m.priet)}
</div>
  • Related