I am trying to add an element into an array after I click the "click me" button.
I did a console log to make sure it went inside the function, but despite the function being call, nothing changes.
I also try using useEffect to check if my variable got update
useEffect(() => {
console.log("cardData ", test);
}, [test]);
Really need some advice on where did i go wrong
This is my codesandbox link
>Solution :
The issue is that you directly mutate the test (test.unshift does mutate the test instance) and rendering does not happen since no reference change was detected (shallow reference is used when rendering happens).
Try this
const onChange = () => {
console.log("onChange");
const testCopy = [...test];
testCopy.unshift("4");
setTest(testCopy);
};
Code sandbox => https://codesandbox.io/s/dark-wildflower-lkf4u?file=/src/App.js:160-302
Another NOT working case can be given like below due to using the same instance reference (test).
const onChange = () => {
console.log("onChange");
test.unshift("4");
setTest(test);
};