• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: React two different useState change at the same time

Resolved: React two different useState change at the same time

0
By Isaac Tonny on 04/04/2023 Issue
Share
Facebook Twitter LinkedIn

In this post, we will see how to resolve React two different useState change at the same time

Question:

This is a simple form table with two states – one (employees) is to keep track of the updated form value, and the other (records) should have saved the form values only when the add/save button is clicked.
The issue is that whenever handleChange is called, it starts to update both the states, which is very weird since setRecords is not called in there.
what am I doing wrong that causes the two states to change together?
I suspect that it has something to do with how I initialized the two states here. What is the correct way to do it then?
Full codes are here:
enter image description here

Best Answer:

Right here you are mutating the original object:
Note objects in JS are always passed by reference. Both arrays are holding references to the same objects.
You should instead create a new employee so as not to mutate the original:
Note that the spread operator {...emp} only duplicates the object one level deep. If one of the object’s properties was another object, the spread operator would not duplicate the nested object. Sometimes it’s better to duplicate your objects before passing them as the default value to useState. Generally you’d use a class constructor or a function for that. Something to keep in mind.

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

javascript reactjs
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to stop a thread that has a blocking function from easygui in python

05/04/2023

Resolved: Removing null keys from a json array of objects

05/04/2023

Resolved: How can I generate at compile-time a separate OpenAPI Swagger.json file for each Controller in my ASP.NET project?

05/04/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.