Search code examples
reactjscreate-react-appreact-bootstrap

In react with hooks, how do I copy and array, and then reverse it?


I have 2 arrays:

function App() {
  const [historyText, setHistoryText] = useState([]);
  const [reversedHistoryText, setReversedHistoryText] = useState([]);

The historyText is working fine, but I want to reverse it. So I thought I would first copy the array to a temp array: I tried this:

setReversedHistoryText([...reversedHistoryText, historyText]);

and

setReversedHistoryText(historyText);

But neither way actually copied the array to the new array. What am I doing wrong?

** Update I'm now able to add it to another array, but its missing the last entry each time.

    setHistoryText([...historyText, tempComp]);
    setReversedHistoryText(historyText.slice().reverse());

Solution

  • You were close but also forgot to reverse it.

    Because state updates are asynchronous, you can't get the latest state right after you call the state updater.

    If this is the only place where historyText and setReversedHistoryText gets updated, you can just append and prepend the new item into the arrays

    setHistoryText([...historyText, tempComp])
    setReversedHistoryText([tempComp, ...reversedHistoryText])
    

    If you need to update setReversedHistoryText only in this function you can create the next historyText array and then use that value to update the reversed array

    const nextHistory = [...historyText, tempComp]
    setHistoryText(nextHistory)
    
    // then
    setReversedHistoryText([...nextHistory].reverse())
    
    // other variations
    setReversedHistoryText(nextHistory.slice().reverse())
    
    setReversedHistoryText(Array.from(nextHistory).reverse())