Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

100
Views
React Typescript: Two different States are Updating

I have two different States from the same class.

For some reason, both get updated through this.setState({selectedRecord: newValue}):

selectedRecord: ModelClass,
question: Array<ModelClass>,

The state question is used in a Table for rendering all data, and the state selectedRecord is a copy of the selected Row, which is used to modify the Row via an Form.

<Button type="primary" icon={<EditOutlined />} onClick={() => {
      this.setState({ selectedRecord: record }, () => {
      this.setState({ modalVisible: true });
   });
}} />

So in the Form I modify the state selectedRecord via Input, Checkbox... and complete it with an setState, but the problem is that the changes are also mutate the question State.

7 months ago · Santiago Trujillo
2 answers
Answer question

0

your dropdownItems has been mutated, try this to retrieve data from your dropdownItems Temp.group = [...this.state.dropdownItems][index].group

7 months ago · Santiago Trujillo Report

0

When you do this:

let Temp = this.state.selectedRecord;
Temp.group = this.state.dropdownItems[index].group;
Temp.free = this.state.dropdownItems[index].free;

...you actually modify the properties (mutate) your previously selected record. Therefore you now make it look like your next selected one. And it affects your question state if it contains a reference to that previous record.

It is unclear why you seem to need to retrieve your previously selected record in the first place, rather than just setting the next one with e.g.:

// No need for Temp at all
this.setState({ selectedRecord: this.state.dropdownItems[index] });
7 months ago · Santiago Trujillo Report
Answer question
Find remote jobs