Why isn't the data rendered in sorted order

Viewed 44

Why isn't the rendered data in sorted order

I am passing rides as a prop in the NearestRides component and inside the NearestRides component, first i am sorting the rides and setting to sortedRides and then i am mapping sortedRides.

but why is the sortedRides not sorted?

is sortedRides getting rendered before getting sorted? if so, how do i sort rides before rendering?

Rides.js

import { useEffect, useState } from "react";
import Navbar from "./Navbar";
import NearestRides from "./NearestRides";

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


  useEffect(() => {
    const fetchRides = async () => {
      const data = await fetch('https://assessment.api.vweb.app/rides');
      const json = await data.json();
      setRides(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 () => {
      rides.map(async (ride) => {
        ride.distance = await calculateDistance(
          ride.station_path,
          user.station_code
        );
      });
    };

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

  return (
    <div>
      <Navbar user = {user}/>
      <div className="home">
        <NearestRides rides = {rides}/>
      </div>
    </div>
  );

}

export default Rides;

NearestRides.js

import { useEffect, useState } from "react";

const NearestRides = ({rides}) => {
  const [sortedRides, setSortedRides] = useState([]);

  useEffect(() => {
    const sortRides = async() => {
      const sorted = await rides.sort((ride1,ride2) => {
        return ride1.distance > ride2.distance ? 1 : -1;
      })

      setSortedRides(sorted);
    }

    sortRides().catch((e) => console.log(e));

  }, [rides]);

  return(
    <div className="rides">
      {console.log(sortedRides)}
      {sortedRides?.map((ride) => {
        return (
          <div className="ride-detail">
          <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>
  )
}

export default NearestRides;
1 Answers

It looks like that when you are calculating the distance and adding the distance property to rides array, you are not actually setting it again to the rides using setRides.

And so, the distance is never part of the rides array when received in child nearestRides and hence sorting method is not working in nestedRides.

But setting the rides in the useEffect with deps will create infinite loop.

So suggest to calculate the distance in the useEffect with no deps - ie right after you fetch the rides.

Related