Travis Clark
Travis Clark

Reputation: 47

React: Why is my child component updating the state of its parent?

I'm just making a simple form component that reads in the user information and displays it in the form as values. After being edited the change can be saved or canceled. However the local state updates it's parent state which has got me scratching my head.

I have a parent component with a user info object inside its state object:

 usrInfo: {
    userName: {name: 'usrname', title: "User Name", value: 'state.user'}, 
    firstName: {name: 'fname', title: "First Name", value: "asdf"},  
    lastName: {name: 'lname',  title: "Last Name", value: "asdf"}, 
    title: {name: 'title', title: "Title", value: "asdf" }, 
    email: {name: 'email',title: "E-mail",value: "[email protected]"}
  },

my child component displays this state no problem. An edit button is clicked in the child and calls a function also in the child to set the userCashe child state to it's parrent user state:

  casheState() {;
    this.setState((prevState, props) => { 
        return {userInfoCashe: props.user };
    })
  }

then a form populates with the userInfoCash as values and when edited it updates the child state:

  changeHandler = (event) => {
    let usrCopy = {...this.state.userInfoCashe};
    usrCopy[event.target.id].value = event.target.value;
    this.setState({userInfoCashe: usrCopy});

    console.log(this.state.userInfoCashe[event.target.id].value)
    console.log(this.props.user[event.target.id].value)
            // ^^ these are the same, why?
  };

this function mutates it's parent user state. HOW AND WHY IS THIS HAPPENING?! I thought that react was built on one-way data binding.

Thanks!

Upvotes: 0

Views: 64

Answers (2)

Sachin Dane
Sachin Dane

Reputation: 258

first I would like to suggest to use lodash npm it will support javascript functions

reference link : https://www.npmjs.com/package/lodash

install lodash : npm install --save lodash

after installing it import it in your file wherever you want to use

    import _ from "lodash";


    changeHandler = (event) => {
    let usrCopy = _.cloneDeep(...this.state.userInfoCashe);

    usrCopy[event.target.id].value = event.target.value;
    this.setState({userInfoCashe: usrCopy});

    console.log(this.state.userInfoCashe[event.target.id].value)
    console.log(this.props.user[event.target.id].value)
            // ^^ these are the same, why?
  };

please try this, it will not update you original state it will update only the where took the copy of state.

Upvotes: 1

Arpit Agrawal
Arpit Agrawal

Reputation: 1180

this.setState doesn't update the state immediately. Its async. So if your console.log shows the same state before and after, then its because of this only. You can try doing something like this :

this.setState({userInfoCashe: usrCopy}, ()=> {console.log(this.state.userInfoCashe);})

to actually see if your state got mutated. Hope this helps.

Upvotes: 2

Related Questions