Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda