Home > Software design >  Why isn't the data rendered in sorted order
Why isn't the data rendered in sorted order

Time:06-11

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;

CodePudding user response:

In NearestRides you do rides.sort() which is an inline sort that means the array stays the same reference and items in it will move to sorted places. Actually, the array got sorted but not got rendered.

For React to rerender an array it should be changed to a new reference. You can simply do it by making a duplicate and setting it. The easiest way is to use the Edit practical-butterfly-wymlnk

CodePudding user response:

If you check for sortedRides at the start of the return in your NearestRides.js it fix it. The fetch and the sort function are both called async, rendering it before sorting it. This way it will wait for it to be sorted.

NearestRide:

  return( sortedRides &&
    <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>
  )
}

Codesandbox demo:https://codesandbox.io/s/mystifying-elion-8kr5up?file=/src/NearestRides.js

CodePudding user response:

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

  • Related