Search code examples
javascriptreactjscomponents

react updating state of one object changing the other object


In my component two objects are based on this one json file. But when I try to change a value in one object the other object just updates automatically. How can I just change value of a field in one object and not the other. My code is

import React, { Component } from 'react';
import quest from './questions.json';

class Quest extends Component {

    constructor(){
        super();
        this.state = {
            questions: quest,
            keyquest: quest
        }
    }

    componentDidMount(){
        this.changequest(this.state.questions);
    }

    changequest(quests){
        quests.map((data) => {
            data.answer = 'changed value';
        })
        this.setState({questions: quests});
    }

    render() {
        console.log(this.state.questions[0].answer);
        console.log(this.state.keyquest[0].answer);
        return (
            <div>
                <h1>Test</h1>
            </div>
        );
    }
}
export default Quest;

the out put of the two console.log statements is the same 'changed value'. What I am doing wrong.


Solution

  • You can try stringify-ing quest in your state and parsing it back in changeQuest method, that way you are not mutating the same object.

    this.state = {
          questions: JSON.stringify(quest),
          keyquest: JSON.stringify(quest)
        };
    
    changequest(quests) {
        const q = JSON.parse(quests);
        this.setState({
          questions: q.map(data => {
            data.answer = "changed value";
            return data;
          })
        });
      }