I have a component I'm importing in a page and I'm creating a sort by option.
I'm using .map for the component. Something like:
{data.posts.map((post) => (
<Box>
<Heading>{post.title}</Heading>
<Box>{post.content}</Box>
</Box>
))}
Then I import that component:
<Posts data={data} />
Now I tried to do something along the lines of using .reverse()
Where I use useState and toggle between ascending and descending then attach that to Posts.
<Posts data={data} sortBy={order} />
and inside the component:
{sortBy === "ascending"
? data.posts.map((post) => (
<Box>
<Heading>{post.title}</Heading>
<Box>{post.content}</Box>
</Box>
))
: data.posts.reverse().map((post) => (
<Box>
<Heading>{post.title}</Heading>
<Box>{post.content}</Box>
</Box>
))}
The default is set to ascending and it displays fine and when I sort by descending it works but if I try to sort back to ascending it doesn't do anything. It remains in descending. Only when I click descending again does it go back to normal. So ascending works great for first loading the page, and then I have to use descending to switch between orders.
Now I could have maybe used this and just initially load ascending then use reverse for both ascending and descending but I have a Dark/Light mode button trigger and when clicked it causes the order to trigger as well due to the change of state.
I was hoping to avoid having to make another API call and apply the sorting via the call but is that really the only option?
reversefunction modifies in place (modifies the original list). One option would to be clone then reverse e.g.[...data.posts].reverse().map(). Or re-sort the list each time sortBy changes, and simply display the list as is (post-sorting)..sort()and pass in a callback sorting the elements how you want.