Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
Using two useEffect but component is returning after executing first one only

Here on rendering (inside return() of the Rides component), ride.distance is undefined but when in second useEffect inside map function on printing each ride they have ride.distance some value and not defined

Is the component renders after execcuting the first useEffect and the second useEffect runs later or there is some other issue?

how do is achieve that, before rendering the second useEffect completes execution ?

import Navbar from "./Navbar";

const Rides = () => {
  const [rides, setRides] = useState([]);
  const [user, setUser] = useState({});
  const [updatedRides, setUpdatedRides] = useState([]);


  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch('https://assessment.api.vweb.app/rides');
      const json = await data.json();
      setRides(json);
      console.log(json);
    }

    const fetchUser = async () => {
      const data = await fetch('https://assessment.api.vweb.app/user');

      const json = await data.json();
      console.log(json);
      setUser(json);
    }
    
    const makeNetworkCalls = async() => {
      await fetchRides();
      await fetchUser();
    }

    makeNetworkCalls().catch((e) => {
      console.log(e);
    })

  }, [])

  useEffect(() => {
    const calculateDistance = async(path, user_station) => {
      let min = Math.abs(user_station - path[0]);
      for(let i = 0; i<path.length; i++){
        if(path[i] === user_station){
          return 0;
        }
        if(Math.abs(path[i] - user_station) < min){
          min = Math.abs(path[i] - user_station);
        }
      }
      return min;
    }

    const updaterides = async() => {
      setUpdatedRides(rides);

      updatedRides.map(async(ride) => {
        ride.distance = await calculateDistance(ride.station_path, user.station_code);
        console.log(ride);
      })
    }

    updaterides().catch((e) => {
      console.log(e);
    })

  }, [rides]);

  return(
    <div>
      <Navbar user = {user}/>
      <div className="rides">
        {updatedRides.map((ride) => {
          return (
            <div className="rideDetail">
              <img src = {ride.map_url} alt="Ride_map" />
              <div>
                <p>Ride Id : {ride.id}</p>
                <p>Origin Station : {ride.origin_station_code}</p>
                <p>Station Path : {ride.station_path}</p>
                <p>Date : {ride.date}</p>
                <p>Distance : {ride.distance}</p>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )

}

export default Rides;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I fixed your code check it out here https://codesandbox.io/embed/busy-payne-qiiw5r?fontsize=14&hidenavigation=1&theme=dark . Problem was related with non async behaviour. In your second useEffect inside updaterides function, you are setting updatedRides then you are mapping it but it does not work as you expected since state changes are not updating immediately before map.

import { useEffect, useState } from "react";

const Rides = () => {
  const [rides, setRides] = useState([]);
  const [user, setUser] = useState({});
  const [updatedRides, setUpdatedRides] = useState([]);

  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch("https://assessment.api.vweb.app/rides");
      const json = await data.json();
      setUpdatedRides(json);
      setRides(json);
    };

    const fetchUser = async () => {
      const data = await fetch("https://assessment.api.vweb.app/user");
      const json = await data.json();
      setUser(json);
    };

    const makeNetworkCalls = async () => {
      await fetchRides();
      await fetchUser();
    };

    makeNetworkCalls().catch((e) => {
      console.log(e);
    });
  }, []);

  useEffect(() => {
    const calculateDistance = async (path, user_station) => {
      let min = Math.abs(user_station - path[0]);
      for (let i = 0; i < path.length; i++) {
        if (path[i] === user_station) {
          return 0;
        }
        if (Math.abs(path[i] - user_station) < min) {
          min = Math.abs(path[i] - user_station);
        }
      }
      return min;
    };

    const updaterides = async () => {
      setUpdatedRides(rides);

      updatedRides.map(async (ride) => {
        ride.distance = await calculateDistance(
          ride.station_path,
          user.station_code
        );
        console.log(ride);
      });
    };

    if (updatedRides?.length > 0 && rides?.length > 0) {
      updaterides().catch((e) => {
        console.log(e);
      });
    }
  }, [rides, updatedRides]);

  return (
    <div>
      <div className="rides">
        {rides?.map((ride) => (
          <div className="rideDetail">
            <img src={ride.map_url} alt="Ride_map" />
            <div>
              <p>Ride Id : {ride.id}</p>
              <p>Origin Station : {ride.origin_station_code}</p>
              <p>Station Path : {ride.station_path}</p>
              <p>Date : {ride.date}</p>
              <p>Distance : {ride.distance}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default Rides;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda