I have an array that looks similar to this
const chapters= [
{ index:1, title:'chapter-1', lessons:[] }
{ index:2, title:'chapter-2', lessons:[] }
{ index:3, title:'chapter-3', lessons:[] }
]
And this comes already sorted from backend on the basis of index
Now I want to create a state of chapters array in react by this approach
chapters.forEach(chapter=>{
this.setState((prevState) => {
return {
...prevState,
chapters: [
...prevState.chapters,
{
chapterTitle: chapter.title,
chapterIndex: chapter.index,
lessons,
},
],
};
});
});
the problem is the state is not sorted. I even tried to sort the states after they have been written once. For that I follwed this code i found in stackoverflow
const sortedChapters= this.state.chapters.sort((a, b) =>
a.index > b.index ? 1 : b.index > a.index ? -1 : 0
);
this.setState({ chapters: sortedChapters});
But no luck. please tell me what I am doing wrong here?
sortdoes mutate the original array. So yoursetStateis probably not triggering a re-render. This could be part of your problem.