Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The data is not updated when useState uses setState

I have a very simple useState use code as follows:

const [roomNumber, setRoomNumber] = React.useState([]);
 setRoomNumber((prev) => {
      const next = prev;
      next.push('');
      return next;
    });

In my understanding, setState was used to update the data and the data should be updated normally after return was used. Why did it not update when I used this method? I also used useEffect to print without any effect

However, if I go back to vscode to save the code, these push contents will all be displayed at once. I have tried this for many times. I want to know whether the way I used setState is wrong or there is a problem with the scaffolding of vite?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am wondering if the new version has changed the content of useState or is there something that I have no idea about at the moment

This is my page.json file:

  "dependencies": {
    "@ant-design/icons": "^5.3.7",
    "@reduxjs/toolkit": "^2.2.1",
    "antd": "^5.18.3",
    "less": "^4.2.0",
    "less-loader": "^12.2.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^9.1.0",
    "react-router-dom": "^6.22.2",
    "redux-persist": "^6.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.55",
    "@types/react-dom": "^18.2.19",
    "@typescript-eslint/eslint-plugin": "^6.21.0",
    "@typescript-eslint/parser": "^6.21.0",
    "@vitejs/plugin-legacy": "^5.3.0",
    "@vitejs/plugin-react": "^4.2.1",
    "electron": "^29.0.0",
    "electron-builder": "^24.12.0",
    "eslint": "^8.56.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.5",
    "typescript": "^5.2.2",
    "vite": "^5.1.0"
  }

>Solution :

you are updating the variable using push method in your example, as a result you return the same reference as before so it doesn’t detect any change.

You just need to return a new reference like this :

setRoomNumber((prev) => [...prev, '']);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading