0

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.

2
  • 1
    what do you mean by it doesn't work, what's your output in the page Commented May 11, 2021 at 16:36
  • Yeah. Not getting sorted stories in page Commented May 11, 2021 at 16:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

9 Comments

Not Working the cdode
Did you try the edited code too? Isn't that too working?
If I edit it works but it should work automatically
array.sort returns a sorted array as well actually.. right?
@HamzaAfzal the edited code works because you are basically using the mutated array. React doesnt understand that the state has changed if you mutate the state. So you need to use the spread operator to create a new array and the sort that array
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.