'Diverting incoming array item from one variable to another in ReactJS
It's a bit of a contrived example below, but it illustrates my problem well. On click, 'a' gets passed a couple of items and I want to make sure the last one gets diverted to 'b' automatically instead of 'a' as part of the same click handler. After the function ran, I would like to see the following state rendered: a = ['Adam', 'Brett'] and b = ["Donald", "Eric", "Fred", "Cody"]
Creating a copy to use the pop method as per below doesn't work as the new state for 'a' hasn't been reflected yet. Any hints welcome.
import React, { useState } from "react";
export default function Test() {
const [a, SetA] = useState([]);
const [b, SetB] = useState(["Donald", "Eric", "Fred"]);
function click() {
SetA((prev) => [...prev, "Adam", "Brett", "Cody"]);
const aCopy = [...a];
const mover = aCopy.pop();
SetA((prev) => [...prev, aCopy]);
SetB((prev) => [...prev, mover]);
}
return (
<>
<div>Group A: {a}</div>
<div>Group B: {b}</div>
<button onClick={click}>Click</button>
</>
);
}
Solution 1:[1]
From React's documentation:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
TLDR; you can't access state right after setState.
What you can do instead is to create 2 new arrays with the values you wanted, and setState after, something like this:
function click() {
const newA = [...a, "Adam", "Brett", "Cody"];
const newB = newA.slice(0, newA.length - 1);
SetA(newA);
SetB(newB);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Belkacem Yahiaoui |
