How do I fix the below code so that the state of Group A gets updated and rendered correctly? On click people from Group A should move to Group B. My hunch is something with useEffect, but I can't think of a way to implement this as aCopy only exists within the click handler.
code:
import React, { useEffect, useState } from "react";
export default function Test() {
const [a, SetA] = useState(["Adam", "Brett", "Cody"]);
const [b, SetB] = useState(["Donald", "Eric", "Fred"]);
function click() {
const aCopy = a;
const mover = aCopy.pop();
SetA(aCopy);
SetB((prev) => [...prev, mover]);
}
return (
<>
<div>Group A: {a}</div>
<div>Group B: {b}</div>
<button onClick={click}>Click</button>
</>
);
}```
You can use the Array.prototype.filter() method to filter the clicked item to remove it from one group while using the spread operator(...) to add it to the other group.
const handleClickA = (item) => {
SetA((prevA) => prevA.filter((o) => o !== item));
SetB((prevB) => [...prevB, item]);
};
This would work as you want. It can move items in between the groups as you expect.
handleClickA and handleClickB are almost same. You can reduce this to a single function if the information about the group is also available for each item.
function Test() {
const [a, SetA] = React.useState(["Adam", "Brett", "Cody"]);
const [b, SetB] = React.useState(["Donald", "Eric", "Fred"]);
const handleClickA = (item) => {
SetA((prevA) => prevA.filter((o) => o !== item));
SetB((prevB) => [...prevB, item]);
};
const handleClickB = (item) => {
SetB((prevB) => prevB.filter((o) => o !== item));
SetA((prevA) => [...prevA, item]);
};
return (
<div>
<div>
Group A:{" "}
{a.map((itemA, indexA) => (
<button key={indexA} onClick={() => handleClickA(itemA)}>
{itemA}
</button>
))}
</div>
<div>
Group B:{" "}
{b.map((itemB, indexB) => (
<button key={indexB} onClick={() => handleClickB(itemB)}>
{itemB}
</button>
))}
</div>
</div>
);
}
ReactDOM.render(<Test />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>