0

After i click on a "person" i request data from api. The data I'm getting is going to state "vehicles', data includes objects with fields "name" and "model" of the vehicle.

const [vehicles, setVehicles] = useState([]);

  useEffect(() => {
    setVehicles([]);
    const fetchVehicles = () => {
      let result = [];
      let personVehicle = person.vehicles;

      personVehicle?.map((el) => {
        return axios.get(el).then((response) => {
          result.push({ name: response.data.name, model: response.data.model });
          setVehicles(result);
        });
      });
    };
    fetchVehicles();
  }, [person]);

How can I render this async data ? How should I loop through it in a correct way ?

I need to get it like this:

<p>Name: {name from state}</p>
<p>Model: {model from state}</p>
3stacks
  • 33
  • 5
  • 1
    Does this answer your question? [How to render an array of objects in React?](https://stackoverflow.com/questions/41374572/how-to-render-an-array-of-objects-in-react) – Chayim Friedman Jan 29 '21 at 00:53

1 Answers1

1

Maybe just add your fetched data to the state, then map through it as a ul?

import React from "react";

const App = () => {
  useEffect(() => {
    fetchVehicles();
  }, []);

  const fetchVehicles = () => {
    axios.get("/api/vehicles").then((res) => {
      const vehicles = res.data;
      vehicles &&
        vehicles.map((v) => {
          setVehicles([...vehicles, { name: v.name, model: v.model }]);
        });
    });
  };

  return (
    <div>
      {vehicles ? (
        <ul>
          {vehicles.map((v) => {
            return (
              <li>
                <p>{v.name}</p>
                <p>{v.model}</p>
              </li>
            );
          })}
        </ul>
      ) : (
        <p>no vehicles</p>
      )}
    </div>
  );
};

export default App;
twominds
  • 1,084
  • 5
  • 20
  • i don't know why, but when you setVehicles in useEffect it returns only one value in the state, not two. – 3stacks Jan 29 '21 at 00:35
  • @3stacks oops, I think i messed up, check out the updated code instead, I think you need to get all your response data of vehicle objects into an array, then for each vehicle object, map and save them to the state. I also forgot to delete the original setVehicles([]) function. – twominds Jan 29 '21 at 00:51