Issue
I have the following codes for a next page using Typescript:
import { NextPage } from "next";
import { useState } from "react";
const Test: NextPage = () => {
const initList = ["a", "b", "c"];
const [list, setList] = useState<Array<String>>(initList);
const handleClick = () => {
var listTemp = list;
listTemp.push("z");
setList(listTemp);
}
return (
<div>
{list.map((item) => (
<h1>{item}</h1>
))}
<button onClick={handleClick}>
Button
</button>
</div>
);
};
export default Test;
My expected behavior is when I click the button the list
expands while the page gets rendered.
But apparently, the state has been changed but the component does not.
Is there any misunderstanding of mine here?
Solution
You are mutating the state object.
const handleClick = () => {
var listTemp = list; // <-- listTemp is reference to list state
listTemp.push("z"); // <-- mutates the array
setList(listTemp); // <-- save same reference back into state
}
The issue is that a new array reference was never created, so React doesn't "see" that state was actually updated.
Create a shallow copy of the array and append new elements into the new array reference that is created.
const handleClick = () => {
setList(list => [...list, "z"]);
}
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.