So I was reading StackOverflow questions and I found this one helpful, on different ways to change the state.
Now if I do something like this, I don't get my alert on state change. So would like to know if this is a bad approach ?? It was mentioned in the above question (most upvoted answer) that we can do something like this.
export default function Test() {
const [firstList, setFirstList] = useState([{ a: "2" }, { b: "3" }]);
const [secondList, setSecondList] = useState([{ c: "4" }, { d: "5" }]);
useEffect(() => {
alert(JSON.stringify(firstList) + " list is merged");
},[firstList]);
function mergeList() {
let previous = firstList;
secondList.forEach((d) => previous.push(d));
setFirstList(previous);
}
return <button onClick={mergeList}>Click</button>;
}
I can anyhow write my function this way and get my alert.
function mergeList() {
secondList.forEach((d) => setFirstList((firstList) => [...firstList, d]));
}
So would like to know if the first approach is badly written?