skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 )

    const { state } = useLocation();
    const datos = state;
    const pasajeros = [];
    
    for (let i = 0; i < datos.length; i++) {
        pasajeros.push({ nombre: datos.nombres[i], apellidos: datos.apellidos[i], DNI: datos.DNI[i] })
    }
    console.log(pasajeros)
    

  2. 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:

    1. Collect all the passengers in an array.
    2. Set the state with this array after the loop.
    const { state } = useLocation();
    const [datos] = useState(state);
    const [pasajeros, setPasajeros] = useState([]);
    
    useEffect(() => {
        const collectedPasajeros = [];
        for (let i = 0; i < datos.nombres.length; i++) {
            collectedPasajeros.push({
                nombre: datos.nombres[i],
                apellido: datos.apellidos[i],
                DNI: datos.DNI[i],
            });
        }
        setPasajeros(collectedPasajeros);
    }, [datos]);
        
    useEffect(() => {
        console.log(parajeros);
    },[parajeros]};
    
    Login or Signup to reply.
  3. 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.

    import React from 'react';
    import { useLocation } from 'react-router-dom';
    
    const YourComponent = () => {
        const { state } = useLocation();
        const datos = state;
    
        const pasajeros = datos.nombres.map((_, index) => ({
            nombre: datos.nombres[index],
            apellido: datos.apellidos[index],
            DNI: datos.DNI[index],
        }));
    
        console.log(pasajeros);
    
        return (
            <div>
                {pasajeros.map((pasajero, index) => (
                    <div key={index}>
                        <p>Nombre: {pasajero.nombre}</p>
                        <p>Apellido: {pasajero.apellido}</p>
                        <p>DNI: {pasajero.DNI}</p>
                    </div>
                ))}
            </div>
        );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search