Skip to content
Advertisement

Set initial class variable from axios request in React

When i call this function

JavaScript

it updates the array questions in state and array initialQuestions variable in constructor. The state questions represents the values form inputs. The inputs are handled in child component with this code

JavaScript

setQuestions is passed in props as setQuestions={(state) => this.setState({ questions: state })} So when i change the value of inputs the onChange function is called and it changes the parent component questions in state. But the parent variable this.initialQuestions also is being changed to the questions value from state, but I don’t know why

Edit:

That’s the code you should be able to run

JavaScript
JavaScript

Advertisement

Answer

Both state questions and class variable initialQuestions hold reference of res.data. Now when you update questions in onChange method, you are updating it by reference i.e directly mutating it and hence the class variable is also updated

You must not update it by reference but clone and update like below

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement