Home > other >  NextJs Typescript - the component does not update when setState called
NextJs Typescript - the component does not update when setState called

Time:12-31

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?

CodePudding user response:

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"]); 
}

CodePudding user response:

** when you console listTemp nothing will happen.*

const listTemp = list -------------> not work;

const listTemp = [...list] --------> will work fine;

now listTemp have all list array value.

const listTemp = [...list, 'z'] -------> Ans ["a", "b", "c", "z"];

  • Related