1

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?

2
  • The reverse function 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). Commented Mar 6, 2021 at 1:33
  • Alternatively, use .sort() and pass in a callback sorting the elements how you want. Commented Mar 6, 2021 at 1:36

1 Answer 1

2

The reverse function modifies the list in place (it modifies the original list). Because you don't undo that reversal, it stays reversed.

One option would to be shallow copy/clone the list and then reverse it:

[...data.posts].reverse().map(post => { })

Or you could re-sort the list each time sortBy changes, and simply display the list as is (post-sorting).

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

Comments

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.