Search code examples
arraysreactjssortinguse-effectuse-state

React.js sort data in useEffect


I have a useState hook name stories.

const [stories, setStories] = useState([
{
      name: "1st Story",
      sid: 1,
      apartmentDetails: [],
},{
      name: "2nd Story",
      sid: 2,
      apartmentDetails: [],
}
]); 

Now I want to add apartmentDetails in 1st Story. To achieve this functionality I am doing the following.

let story = stories.find((story) => story.sid == storyID);
    const storyWithDetails = {
      ...story,
      appartmentDetails: [
        ...story.appartmentDetails,
        {
          apartment_name: apratmentName,
          apartment_num: apratmentNum,
          apartment_type: apartmentType,
          areaDetails: [],
        },
      ],

But it's rearranging the stories by putting the 1st Story at the last of the array. I used useEffect hook to sort it

  useEffect(() => {
    setStories(stories.sort((a, b) => parseInt(a.sid) - parseInt(b.sid)));
    console.log(stories);
  }, [stories]);

the log is returning me the sorted stories but in HTML/JSX it's not working.


Solution

  • Array.sort() sorts the array in-place.

    Try storing it to another variable and setting the state.

    Like,

    useEffect(() => {
        const newStories = [...stories];
        newStories.sort((a, b) => parseInt(a.sid) - parseInt(b.sid));
        setStories(newStories);
      }, [stories]);
    

    Caution: setStories() inside a useEffect() with dependency as [stories] can cause infinite loop. But the core idea is same above.

    Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort