i’m learning reactJS and in this case i’m trying to assign passangers to a variable so i can later loop their name, ID..
I’m getting data from a formdata from a different file:
-Name
-Forename
-ID
I’m getting the data from "datos" variable so if in my for loop i’m getting datos.nombre in a correct way but cosole loging pasajero only logs the last person.
const { state } = useLocation();
const [datos] = useState(state);
const [pasajero, setPasajero] = useState({})
useEffect(() => {
for (let i = 0; i < datos.length; i++) {
setPasajero((prev) => ({
...prev,
nombre: datos.nombres[i],
apellido: datos.apellidos[i],
DNI: datos.DNI[i],
}));
}
},[]);
console.log(pasajero)
in my for loop i tried to assign the passanger but i’m getting the last value when i want to get every person in that for loop
3
Answers
Changed it by creating an empty array and then pushing data while looping through my data using for loop. It works for what i wanted it for (display passanger information) for the payment (which obviously doesn't exist in this project :D )
Your issue is basically happening because of asynchronous nature of state updates in React.
To accumulate all passengers, you need to gather all the data fisrt and then set the state once after that.
Here’s step you can try for:
This approach is simpler and avoids the unnecessary complexity of state management when the data is static and derived directly from props or location state.