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>
1

1 Answer 1

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;

Sign up to request clarification or add additional context in comments.

2 Comments

i don't know why, but when you setVehicles in useEffect it returns only one value in the state, not two.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.