Home > other >  Why does reverse() not work when it's done before the array is re-assigned, but works when it&#
Why does reverse() not work when it's done before the array is re-assigned, but works when it&#

Time:12-15

I have multiple components, but only two are relevant to this question - FrontPage and Stream.

At the beginning of FrontPage, I have a useEffect in which I fetch all the posts from the server, and put them inside postsArray, which I then send as prop to the Stream component.

At the bottom of the frontPage component, I do pagination by slicing the postsArray, and creating a new array called 'currentPosts', which I also send as prop to the 'Stream' component. While doing so, I also reverse the order of the posts, and this is where I am having trouble understanding something.

When I reverse the order BEFORE I assign the sliced array to currentPosts, the order is not reversed. But if I do it afterwards, it works.

 let currentPosts = [];
   if(postsArray.length !== 0) { 
        console.log('here')
        //postsArray.reverse()
        currentPosts = postsArray.slice(indexOfFirstPost, indexOfLastPost)
        postsArray.reverse()
   }

This is the relevant part of the code. If the reverse is done before the assignment to currentPosts, the reverse does not work. If it's done right after it, it works. I don't understand why.

If I do the reverse before I slice and assign it to currentPosts, if I then console log the currentPosts and postsArray right before rendering the frontPage component, and right before rendering the Stream component, the console log shows that in the frontPage component, the currentPosts array is not reversed, but in the Stream component, it is reversed, but postsArray is not.

How could this be?

If I do the reverse() after the slicing, then both currentPosts and postsArray are not reversed in both components.

I was thinking that perhaps it takes time for the reverse() is finish executing, and that's why the array is consoled out not reversed right before rendering the frontPage component, but then, once the reverse() has finished executing, how does that overwrites the already assigned currentPosts array in the Stream component, and if that's really what's happening, then why does it not overwrite the postsArray too?

Here's a snapshot of the console log.

enter image description here

CodePudding user response:

One option is to explicitly set postsArray equal to the reversed array.

let currentPosts = [];
if(postsArray.length !== 0) { 
   console.log('here')
   postsArray = postsArray.slice().reverse()
   currentPosts = postsArray.slice(indexOfFirstPost, indexOfLastPost)
   postsArray.reverse()
}

It's daft, but it works

  • Related