Updating an object with setState in React





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







130















Is it at all possible to update object's properties with setState?



Something like:



this.state = {
jasper: { name: 'jasper', age: 28 },
}


I have tried:



this.setState({jasper.name : 'someOtherName'});


and this:



this.setState({jasper:{name:'someothername'}})


The first is Syntax error and the second just does nothing. Any ideas?










share|improve this question




















  • 3





    second code would have worked however you would have lost the age property inside jasper.

    – giorgim
    Jul 10 '18 at 8:14


















130















Is it at all possible to update object's properties with setState?



Something like:



this.state = {
jasper: { name: 'jasper', age: 28 },
}


I have tried:



this.setState({jasper.name : 'someOtherName'});


and this:



this.setState({jasper:{name:'someothername'}})


The first is Syntax error and the second just does nothing. Any ideas?










share|improve this question




















  • 3





    second code would have worked however you would have lost the age property inside jasper.

    – giorgim
    Jul 10 '18 at 8:14














130












130








130


60






Is it at all possible to update object's properties with setState?



Something like:



this.state = {
jasper: { name: 'jasper', age: 28 },
}


I have tried:



this.setState({jasper.name : 'someOtherName'});


and this:



this.setState({jasper:{name:'someothername'}})


The first is Syntax error and the second just does nothing. Any ideas?










share|improve this question
















Is it at all possible to update object's properties with setState?



Something like:



this.state = {
jasper: { name: 'jasper', age: 28 },
}


I have tried:



this.setState({jasper.name : 'someOtherName'});


and this:



this.setState({jasper:{name:'someothername'}})


The first is Syntax error and the second just does nothing. Any ideas?







reactjs state






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 5 '18 at 15:27









Mayank Shukla

42k76787




42k76787










asked Apr 26 '17 at 15:47









JohnSnowJohnSnow

1,10431022




1,10431022








  • 3





    second code would have worked however you would have lost the age property inside jasper.

    – giorgim
    Jul 10 '18 at 8:14














  • 3





    second code would have worked however you would have lost the age property inside jasper.

    – giorgim
    Jul 10 '18 at 8:14








3




3





second code would have worked however you would have lost the age property inside jasper.

– giorgim
Jul 10 '18 at 8:14





second code would have worked however you would have lost the age property inside jasper.

– giorgim
Jul 10 '18 at 8:14












11 Answers
11






active

oldest

votes


















275














There are multiple ways of doing this.



1- Simplest one:



First create a copy of jasper then do the changes in that:



let jasper = Object.assign({}, this.state.jasper);    //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});


Instead of using Object.assign we can also write it like this:



let jasper = {...this.state.jasper};


2- Using spread operator:



this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))





share|improve this answer


























  • The way I was trying now works though... the second way :S

    – JohnSnow
    Apr 26 '17 at 16:05






  • 6





    @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

    – Mayank Shukla
    Apr 26 '17 at 16:07








  • 1





    @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

    – Mayank Shukla
    Apr 26 '17 at 16:16








  • 4





    Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

    – Alex Vasilev
    May 24 '18 at 8:08








  • 1





    How bout let { jasper } = this.state?

    – Brian Le
    Nov 23 '18 at 20:44



















17














Fastest and the most readable way:



this.setState({...this.state.jasper, name: 'someothername'});


Althought this.state.jasper already contain a name property, latter name: 'someothername' with be used.






share|improve this answer



















  • 14





    This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

    – sinned
    Jun 8 '18 at 7:55





















13














Use spread operator and some ES6 here



this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})





share|improve this answer

































    5














    I used this solution.



    If you have a nested state like this:



       this.state = {
    formInputs:{
    friendName:{
    value:'',
    isValid:false,
    errorMsg:''
    },
    friendEmail:{
    value:'',
    isValid:false,
    errorMsg:''
    }
    }


    you can declare the handleChange function that copy current status and re-assigns it with changed values



    handleChange(el) {
    let inputName = el.target.name;
    let inputValue = el.target.value;

    let statusCopy = Object.assign({}, this.state);
    statusCopy.formInputs[inputName].value = inputValue;

    this.setState(statusCopy);
    }


    here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')



    <input type="text" onChange={this.handleChange} " name="friendName" />





    share|improve this answer































      3














      The first case is indeed a syntax error.



      Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:



      this.state = {
      name: 'jasper',
      age: 28
      }


      That way, if you want to update the name, you can just call:



      this.setState({
      name: 'Sean'
      });


      Will that achieve what you're aiming for?



      For larger, more complex data stores, I would use something like Redux. But that's much more advanced.



      The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)



      Check out these references:




      • https://facebook.github.io/react/docs/react-component.html#state

      • https://facebook.github.io/react/docs/state-and-lifecycle.html






      share|improve this answer



















      • 1





        I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

        – JohnSnow
        Apr 26 '17 at 16:07






      • 2





        Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

        – mccambridge
        Apr 26 '17 at 16:39



















      2














      try this,it should work fine



      this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));





      share|improve this answer
























      • I've tried many other methods... but your snippet is rock! thanks man

        – hendra1
        Jan 23 at 13:14













      • Thank you very much for letting me know. I am happy that resolved your problem.

        – Burak Kahraman
        Jan 24 at 15:37



















      0














      Another option: define your variable out of the Jasper object and then just call a variable.



      Spread operator: ES6



      this.state = {  jasper: { name: 'jasper', age: 28 } } 

      let foo = "something that needs to be saved into state"

      this.setState(prevState => ({
      jasper: {
      ...jasper.entity,
      foo
      }
      })





      share|improve this answer





















      • 1





        I am not sure the downvoter(s) understood that foo expands to foo: foo...

        – Cory Silva
        Dec 8 '18 at 16:55





















      0














      Also, following Alberto Piras solution, if you don't want to copy all the "state" object:



      handleChange(el) {
      let inputName = el.target.name;
      let inputValue = el.target.value;

      let jasperCopy = Object.assign({}, this.state.jasper);
      jasperCopy[inputName].name = inputValue;

      this.setState({jasper: jasperCopy});
      }





      share|improve this answer































        0














        You can try with this:
        (Note: name of input tag === field of object)



        <input name="myField" type="text" 
        value={this.state.myObject.myField}
        onChange={this.handleChangeInpForm}></input>

        -----------------------------------------------------------
        handleChangeInpForm = (e) => {
        let newObject = this.state.myObject;
        newObject[e.target.name] = e.target.value;
        this.setState({
        myObject: newObject
        })
        }





        share|improve this answer


























        • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

          – Elletlar
          Jan 28 at 12:51



















        0














        Simple and dynamic way.



        This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.



        handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });





        share|improve this answer

































          -1














          You can try with this:



          this.setState(prevState => {
          prevState = JSON.parse(JSON.stringify(this.state.jasper));
          prevState.name = 'someOtherName';
          return {jasper: prevState}
          })


          or for other property:



          this.setState(prevState => {
          prevState = JSON.parse(JSON.stringify(this.state.jasper));
          prevState.age = 'someOtherAge';
          return {jasper: prevState}
          })


          Or you can use handleChage function:



          handleChage(event) {
          const {name, value} = event.target;
          this.setState(prevState => {
          prevState = JSON.parse(JSON.stringify(this.state.jasper));
          prevState[name] = value;
          return {jasper: prevState}
          })
          }


          and HTML code:



          <input 
          type={"text"}
          name={"name"}
          value={this.state.jasper.name}
          onChange={this.handleChange}
          />
          <br/>
          <input
          type={"text"}
          name={"age"}
          value={this.state.jasper.age}
          onChange={this.handleChange}
          />





          share|improve this answer
























            protected by Community Mar 14 at 18:31



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            11 Answers
            11






            active

            oldest

            votes








            11 Answers
            11






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            275














            There are multiple ways of doing this.



            1- Simplest one:



            First create a copy of jasper then do the changes in that:



            let jasper = Object.assign({}, this.state.jasper);    //creating copy of object
            jasper.name = 'someothername'; //updating value
            this.setState({jasper});


            Instead of using Object.assign we can also write it like this:



            let jasper = {...this.state.jasper};


            2- Using spread operator:



            this.setState(prevState => ({
            jasper: {
            ...prevState.jasper,
            name: 'something'
            }
            }))





            share|improve this answer


























            • The way I was trying now works though... the second way :S

              – JohnSnow
              Apr 26 '17 at 16:05






            • 6





              @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

              – Mayank Shukla
              Apr 26 '17 at 16:07








            • 1





              @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

              – Mayank Shukla
              Apr 26 '17 at 16:16








            • 4





              Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

              – Alex Vasilev
              May 24 '18 at 8:08








            • 1





              How bout let { jasper } = this.state?

              – Brian Le
              Nov 23 '18 at 20:44
















            275














            There are multiple ways of doing this.



            1- Simplest one:



            First create a copy of jasper then do the changes in that:



            let jasper = Object.assign({}, this.state.jasper);    //creating copy of object
            jasper.name = 'someothername'; //updating value
            this.setState({jasper});


            Instead of using Object.assign we can also write it like this:



            let jasper = {...this.state.jasper};


            2- Using spread operator:



            this.setState(prevState => ({
            jasper: {
            ...prevState.jasper,
            name: 'something'
            }
            }))





            share|improve this answer


























            • The way I was trying now works though... the second way :S

              – JohnSnow
              Apr 26 '17 at 16:05






            • 6





              @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

              – Mayank Shukla
              Apr 26 '17 at 16:07








            • 1





              @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

              – Mayank Shukla
              Apr 26 '17 at 16:16








            • 4





              Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

              – Alex Vasilev
              May 24 '18 at 8:08








            • 1





              How bout let { jasper } = this.state?

              – Brian Le
              Nov 23 '18 at 20:44














            275












            275








            275







            There are multiple ways of doing this.



            1- Simplest one:



            First create a copy of jasper then do the changes in that:



            let jasper = Object.assign({}, this.state.jasper);    //creating copy of object
            jasper.name = 'someothername'; //updating value
            this.setState({jasper});


            Instead of using Object.assign we can also write it like this:



            let jasper = {...this.state.jasper};


            2- Using spread operator:



            this.setState(prevState => ({
            jasper: {
            ...prevState.jasper,
            name: 'something'
            }
            }))





            share|improve this answer















            There are multiple ways of doing this.



            1- Simplest one:



            First create a copy of jasper then do the changes in that:



            let jasper = Object.assign({}, this.state.jasper);    //creating copy of object
            jasper.name = 'someothername'; //updating value
            this.setState({jasper});


            Instead of using Object.assign we can also write it like this:



            let jasper = {...this.state.jasper};


            2- Using spread operator:



            this.setState(prevState => ({
            jasper: {
            ...prevState.jasper,
            name: 'something'
            }
            }))






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 7 '17 at 14:03

























            answered Apr 26 '17 at 15:59









            Mayank ShuklaMayank Shukla

            42k76787




            42k76787













            • The way I was trying now works though... the second way :S

              – JohnSnow
              Apr 26 '17 at 16:05






            • 6





              @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

              – Mayank Shukla
              Apr 26 '17 at 16:07








            • 1





              @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

              – Mayank Shukla
              Apr 26 '17 at 16:16








            • 4





              Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

              – Alex Vasilev
              May 24 '18 at 8:08








            • 1





              How bout let { jasper } = this.state?

              – Brian Le
              Nov 23 '18 at 20:44



















            • The way I was trying now works though... the second way :S

              – JohnSnow
              Apr 26 '17 at 16:05






            • 6





              @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

              – Mayank Shukla
              Apr 26 '17 at 16:07








            • 1





              @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

              – Mayank Shukla
              Apr 26 '17 at 16:16








            • 4





              Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

              – Alex Vasilev
              May 24 '18 at 8:08








            • 1





              How bout let { jasper } = this.state?

              – Brian Le
              Nov 23 '18 at 20:44

















            The way I was trying now works though... the second way :S

            – JohnSnow
            Apr 26 '17 at 16:05





            The way I was trying now works though... the second way :S

            – JohnSnow
            Apr 26 '17 at 16:05




            6




            6





            @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

            – Mayank Shukla
            Apr 26 '17 at 16:07







            @JohnSnow in you second it will remove the other properties from jasper object, do the console.log(jasper) you will see only one key name, age will not be there :)

            – Mayank Shukla
            Apr 26 '17 at 16:07






            1




            1





            @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

            – Mayank Shukla
            Apr 26 '17 at 16:16







            @JohnSnow, yes this way is proper if jasper is an object, don't the whether best or not, may be other better solutions are possible :)

            – Mayank Shukla
            Apr 26 '17 at 16:16






            4




            4





            Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

            – Alex Vasilev
            May 24 '18 at 8:08







            Good to mention here that neither Object.assign nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy etc.

            – Alex Vasilev
            May 24 '18 at 8:08






            1




            1





            How bout let { jasper } = this.state?

            – Brian Le
            Nov 23 '18 at 20:44





            How bout let { jasper } = this.state?

            – Brian Le
            Nov 23 '18 at 20:44













            17














            Fastest and the most readable way:



            this.setState({...this.state.jasper, name: 'someothername'});


            Althought this.state.jasper already contain a name property, latter name: 'someothername' with be used.






            share|improve this answer



















            • 14





              This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

              – sinned
              Jun 8 '18 at 7:55


















            17














            Fastest and the most readable way:



            this.setState({...this.state.jasper, name: 'someothername'});


            Althought this.state.jasper already contain a name property, latter name: 'someothername' with be used.






            share|improve this answer



















            • 14





              This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

              – sinned
              Jun 8 '18 at 7:55
















            17












            17








            17







            Fastest and the most readable way:



            this.setState({...this.state.jasper, name: 'someothername'});


            Althought this.state.jasper already contain a name property, latter name: 'someothername' with be used.






            share|improve this answer













            Fastest and the most readable way:



            this.setState({...this.state.jasper, name: 'someothername'});


            Althought this.state.jasper already contain a name property, latter name: 'someothername' with be used.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 17 '18 at 2:47









            mannokmannok

            361313




            361313








            • 14





              This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

              – sinned
              Jun 8 '18 at 7:55
















            • 14





              This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

              – sinned
              Jun 8 '18 at 7:55










            14




            14





            This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

            – sinned
            Jun 8 '18 at 7:55







            This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence this.state.jasper does not necessarily contain the latest state. Better use the notation with the prevState.

            – sinned
            Jun 8 '18 at 7:55













            13














            Use spread operator and some ES6 here



            this.setState({
            jasper: {
            ...this.state.jasper,
            name: 'something'
            }
            })





            share|improve this answer






























              13














              Use spread operator and some ES6 here



              this.setState({
              jasper: {
              ...this.state.jasper,
              name: 'something'
              }
              })





              share|improve this answer




























                13












                13








                13







                Use spread operator and some ES6 here



                this.setState({
                jasper: {
                ...this.state.jasper,
                name: 'something'
                }
                })





                share|improve this answer















                Use spread operator and some ES6 here



                this.setState({
                jasper: {
                ...this.state.jasper,
                name: 'something'
                }
                })






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 5 '18 at 3:15









                Just code

                10.5k53267




                10.5k53267










                answered May 21 '18 at 9:57









                NikhilNikhil

                368211




                368211























                    5














                    I used this solution.



                    If you have a nested state like this:



                       this.state = {
                    formInputs:{
                    friendName:{
                    value:'',
                    isValid:false,
                    errorMsg:''
                    },
                    friendEmail:{
                    value:'',
                    isValid:false,
                    errorMsg:''
                    }
                    }


                    you can declare the handleChange function that copy current status and re-assigns it with changed values



                    handleChange(el) {
                    let inputName = el.target.name;
                    let inputValue = el.target.value;

                    let statusCopy = Object.assign({}, this.state);
                    statusCopy.formInputs[inputName].value = inputValue;

                    this.setState(statusCopy);
                    }


                    here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')



                    <input type="text" onChange={this.handleChange} " name="friendName" />





                    share|improve this answer




























                      5














                      I used this solution.



                      If you have a nested state like this:



                         this.state = {
                      formInputs:{
                      friendName:{
                      value:'',
                      isValid:false,
                      errorMsg:''
                      },
                      friendEmail:{
                      value:'',
                      isValid:false,
                      errorMsg:''
                      }
                      }


                      you can declare the handleChange function that copy current status and re-assigns it with changed values



                      handleChange(el) {
                      let inputName = el.target.name;
                      let inputValue = el.target.value;

                      let statusCopy = Object.assign({}, this.state);
                      statusCopy.formInputs[inputName].value = inputValue;

                      this.setState(statusCopy);
                      }


                      here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')



                      <input type="text" onChange={this.handleChange} " name="friendName" />





                      share|improve this answer


























                        5












                        5








                        5







                        I used this solution.



                        If you have a nested state like this:



                           this.state = {
                        formInputs:{
                        friendName:{
                        value:'',
                        isValid:false,
                        errorMsg:''
                        },
                        friendEmail:{
                        value:'',
                        isValid:false,
                        errorMsg:''
                        }
                        }


                        you can declare the handleChange function that copy current status and re-assigns it with changed values



                        handleChange(el) {
                        let inputName = el.target.name;
                        let inputValue = el.target.value;

                        let statusCopy = Object.assign({}, this.state);
                        statusCopy.formInputs[inputName].value = inputValue;

                        this.setState(statusCopy);
                        }


                        here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')



                        <input type="text" onChange={this.handleChange} " name="friendName" />





                        share|improve this answer













                        I used this solution.



                        If you have a nested state like this:



                           this.state = {
                        formInputs:{
                        friendName:{
                        value:'',
                        isValid:false,
                        errorMsg:''
                        },
                        friendEmail:{
                        value:'',
                        isValid:false,
                        errorMsg:''
                        }
                        }


                        you can declare the handleChange function that copy current status and re-assigns it with changed values



                        handleChange(el) {
                        let inputName = el.target.name;
                        let inputValue = el.target.value;

                        let statusCopy = Object.assign({}, this.state);
                        statusCopy.formInputs[inputName].value = inputValue;

                        this.setState(statusCopy);
                        }


                        here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')



                        <input type="text" onChange={this.handleChange} " name="friendName" />






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 6 '18 at 10:29









                        Alberto PirasAlberto Piras

                        9113




                        9113























                            3














                            The first case is indeed a syntax error.



                            Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:



                            this.state = {
                            name: 'jasper',
                            age: 28
                            }


                            That way, if you want to update the name, you can just call:



                            this.setState({
                            name: 'Sean'
                            });


                            Will that achieve what you're aiming for?



                            For larger, more complex data stores, I would use something like Redux. But that's much more advanced.



                            The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)



                            Check out these references:




                            • https://facebook.github.io/react/docs/react-component.html#state

                            • https://facebook.github.io/react/docs/state-and-lifecycle.html






                            share|improve this answer



















                            • 1





                              I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                              – JohnSnow
                              Apr 26 '17 at 16:07






                            • 2





                              Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                              – mccambridge
                              Apr 26 '17 at 16:39
















                            3














                            The first case is indeed a syntax error.



                            Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:



                            this.state = {
                            name: 'jasper',
                            age: 28
                            }


                            That way, if you want to update the name, you can just call:



                            this.setState({
                            name: 'Sean'
                            });


                            Will that achieve what you're aiming for?



                            For larger, more complex data stores, I would use something like Redux. But that's much more advanced.



                            The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)



                            Check out these references:




                            • https://facebook.github.io/react/docs/react-component.html#state

                            • https://facebook.github.io/react/docs/state-and-lifecycle.html






                            share|improve this answer



















                            • 1





                              I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                              – JohnSnow
                              Apr 26 '17 at 16:07






                            • 2





                              Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                              – mccambridge
                              Apr 26 '17 at 16:39














                            3












                            3








                            3







                            The first case is indeed a syntax error.



                            Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:



                            this.state = {
                            name: 'jasper',
                            age: 28
                            }


                            That way, if you want to update the name, you can just call:



                            this.setState({
                            name: 'Sean'
                            });


                            Will that achieve what you're aiming for?



                            For larger, more complex data stores, I would use something like Redux. But that's much more advanced.



                            The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)



                            Check out these references:




                            • https://facebook.github.io/react/docs/react-component.html#state

                            • https://facebook.github.io/react/docs/state-and-lifecycle.html






                            share|improve this answer













                            The first case is indeed a syntax error.



                            Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:



                            this.state = {
                            name: 'jasper',
                            age: 28
                            }


                            That way, if you want to update the name, you can just call:



                            this.setState({
                            name: 'Sean'
                            });


                            Will that achieve what you're aiming for?



                            For larger, more complex data stores, I would use something like Redux. But that's much more advanced.



                            The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)



                            Check out these references:




                            • https://facebook.github.io/react/docs/react-component.html#state

                            • https://facebook.github.io/react/docs/state-and-lifecycle.html







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Apr 26 '17 at 16:06









                            mccambridgemccambridge

                            764414




                            764414








                            • 1





                              I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                              – JohnSnow
                              Apr 26 '17 at 16:07






                            • 2





                              Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                              – mccambridge
                              Apr 26 '17 at 16:39














                            • 1





                              I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                              – JohnSnow
                              Apr 26 '17 at 16:07






                            • 2





                              Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                              – mccambridge
                              Apr 26 '17 at 16:39








                            1




                            1





                            I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                            – JohnSnow
                            Apr 26 '17 at 16:07





                            I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..

                            – JohnSnow
                            Apr 26 '17 at 16:07




                            2




                            2





                            Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                            – mccambridge
                            Apr 26 '17 at 16:39





                            Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍

                            – mccambridge
                            Apr 26 '17 at 16:39











                            2














                            try this,it should work fine



                            this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));





                            share|improve this answer
























                            • I've tried many other methods... but your snippet is rock! thanks man

                              – hendra1
                              Jan 23 at 13:14













                            • Thank you very much for letting me know. I am happy that resolved your problem.

                              – Burak Kahraman
                              Jan 24 at 15:37
















                            2














                            try this,it should work fine



                            this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));





                            share|improve this answer
























                            • I've tried many other methods... but your snippet is rock! thanks man

                              – hendra1
                              Jan 23 at 13:14













                            • Thank you very much for letting me know. I am happy that resolved your problem.

                              – Burak Kahraman
                              Jan 24 at 15:37














                            2












                            2








                            2







                            try this,it should work fine



                            this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));





                            share|improve this answer













                            try this,it should work fine



                            this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 1 at 12:40









                            Burak KahramanBurak Kahraman

                            213




                            213













                            • I've tried many other methods... but your snippet is rock! thanks man

                              – hendra1
                              Jan 23 at 13:14













                            • Thank you very much for letting me know. I am happy that resolved your problem.

                              – Burak Kahraman
                              Jan 24 at 15:37



















                            • I've tried many other methods... but your snippet is rock! thanks man

                              – hendra1
                              Jan 23 at 13:14













                            • Thank you very much for letting me know. I am happy that resolved your problem.

                              – Burak Kahraman
                              Jan 24 at 15:37

















                            I've tried many other methods... but your snippet is rock! thanks man

                            – hendra1
                            Jan 23 at 13:14







                            I've tried many other methods... but your snippet is rock! thanks man

                            – hendra1
                            Jan 23 at 13:14















                            Thank you very much for letting me know. I am happy that resolved your problem.

                            – Burak Kahraman
                            Jan 24 at 15:37





                            Thank you very much for letting me know. I am happy that resolved your problem.

                            – Burak Kahraman
                            Jan 24 at 15:37











                            0














                            Another option: define your variable out of the Jasper object and then just call a variable.



                            Spread operator: ES6



                            this.state = {  jasper: { name: 'jasper', age: 28 } } 

                            let foo = "something that needs to be saved into state"

                            this.setState(prevState => ({
                            jasper: {
                            ...jasper.entity,
                            foo
                            }
                            })





                            share|improve this answer





















                            • 1





                              I am not sure the downvoter(s) understood that foo expands to foo: foo...

                              – Cory Silva
                              Dec 8 '18 at 16:55


















                            0














                            Another option: define your variable out of the Jasper object and then just call a variable.



                            Spread operator: ES6



                            this.state = {  jasper: { name: 'jasper', age: 28 } } 

                            let foo = "something that needs to be saved into state"

                            this.setState(prevState => ({
                            jasper: {
                            ...jasper.entity,
                            foo
                            }
                            })





                            share|improve this answer





















                            • 1





                              I am not sure the downvoter(s) understood that foo expands to foo: foo...

                              – Cory Silva
                              Dec 8 '18 at 16:55
















                            0












                            0








                            0







                            Another option: define your variable out of the Jasper object and then just call a variable.



                            Spread operator: ES6



                            this.state = {  jasper: { name: 'jasper', age: 28 } } 

                            let foo = "something that needs to be saved into state"

                            this.setState(prevState => ({
                            jasper: {
                            ...jasper.entity,
                            foo
                            }
                            })





                            share|improve this answer















                            Another option: define your variable out of the Jasper object and then just call a variable.



                            Spread operator: ES6



                            this.state = {  jasper: { name: 'jasper', age: 28 } } 

                            let foo = "something that needs to be saved into state"

                            this.setState(prevState => ({
                            jasper: {
                            ...jasper.entity,
                            foo
                            }
                            })






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 15 '18 at 10:54









                            J. Steen

                            10.3k124961




                            10.3k124961










                            answered Feb 20 '18 at 2:28









                            Luis MartinsLuis Martins

                            637510




                            637510








                            • 1





                              I am not sure the downvoter(s) understood that foo expands to foo: foo...

                              – Cory Silva
                              Dec 8 '18 at 16:55
















                            • 1





                              I am not sure the downvoter(s) understood that foo expands to foo: foo...

                              – Cory Silva
                              Dec 8 '18 at 16:55










                            1




                            1





                            I am not sure the downvoter(s) understood that foo expands to foo: foo...

                            – Cory Silva
                            Dec 8 '18 at 16:55







                            I am not sure the downvoter(s) understood that foo expands to foo: foo...

                            – Cory Silva
                            Dec 8 '18 at 16:55













                            0














                            Also, following Alberto Piras solution, if you don't want to copy all the "state" object:



                            handleChange(el) {
                            let inputName = el.target.name;
                            let inputValue = el.target.value;

                            let jasperCopy = Object.assign({}, this.state.jasper);
                            jasperCopy[inputName].name = inputValue;

                            this.setState({jasper: jasperCopy});
                            }





                            share|improve this answer




























                              0














                              Also, following Alberto Piras solution, if you don't want to copy all the "state" object:



                              handleChange(el) {
                              let inputName = el.target.name;
                              let inputValue = el.target.value;

                              let jasperCopy = Object.assign({}, this.state.jasper);
                              jasperCopy[inputName].name = inputValue;

                              this.setState({jasper: jasperCopy});
                              }





                              share|improve this answer


























                                0












                                0








                                0







                                Also, following Alberto Piras solution, if you don't want to copy all the "state" object:



                                handleChange(el) {
                                let inputName = el.target.name;
                                let inputValue = el.target.value;

                                let jasperCopy = Object.assign({}, this.state.jasper);
                                jasperCopy[inputName].name = inputValue;

                                this.setState({jasper: jasperCopy});
                                }





                                share|improve this answer













                                Also, following Alberto Piras solution, if you don't want to copy all the "state" object:



                                handleChange(el) {
                                let inputName = el.target.name;
                                let inputValue = el.target.value;

                                let jasperCopy = Object.assign({}, this.state.jasper);
                                jasperCopy[inputName].name = inputValue;

                                this.setState({jasper: jasperCopy});
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Aug 13 '18 at 9:17









                                Marc LaQuayMarc LaQuay

                                15016




                                15016























                                    0














                                    You can try with this:
                                    (Note: name of input tag === field of object)



                                    <input name="myField" type="text" 
                                    value={this.state.myObject.myField}
                                    onChange={this.handleChangeInpForm}></input>

                                    -----------------------------------------------------------
                                    handleChangeInpForm = (e) => {
                                    let newObject = this.state.myObject;
                                    newObject[e.target.name] = e.target.value;
                                    this.setState({
                                    myObject: newObject
                                    })
                                    }





                                    share|improve this answer


























                                    • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                      – Elletlar
                                      Jan 28 at 12:51
















                                    0














                                    You can try with this:
                                    (Note: name of input tag === field of object)



                                    <input name="myField" type="text" 
                                    value={this.state.myObject.myField}
                                    onChange={this.handleChangeInpForm}></input>

                                    -----------------------------------------------------------
                                    handleChangeInpForm = (e) => {
                                    let newObject = this.state.myObject;
                                    newObject[e.target.name] = e.target.value;
                                    this.setState({
                                    myObject: newObject
                                    })
                                    }





                                    share|improve this answer


























                                    • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                      – Elletlar
                                      Jan 28 at 12:51














                                    0












                                    0








                                    0







                                    You can try with this:
                                    (Note: name of input tag === field of object)



                                    <input name="myField" type="text" 
                                    value={this.state.myObject.myField}
                                    onChange={this.handleChangeInpForm}></input>

                                    -----------------------------------------------------------
                                    handleChangeInpForm = (e) => {
                                    let newObject = this.state.myObject;
                                    newObject[e.target.name] = e.target.value;
                                    this.setState({
                                    myObject: newObject
                                    })
                                    }





                                    share|improve this answer















                                    You can try with this:
                                    (Note: name of input tag === field of object)



                                    <input name="myField" type="text" 
                                    value={this.state.myObject.myField}
                                    onChange={this.handleChangeInpForm}></input>

                                    -----------------------------------------------------------
                                    handleChangeInpForm = (e) => {
                                    let newObject = this.state.myObject;
                                    newObject[e.target.name] = e.target.value;
                                    this.setState({
                                    myObject: newObject
                                    })
                                    }






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jan 30 at 3:47

























                                    answered Jan 28 at 12:31









                                    Xuanduong NgoXuanduong Ngo

                                    11




                                    11













                                    • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                      – Elletlar
                                      Jan 28 at 12:51



















                                    • Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                      – Elletlar
                                      Jan 28 at 12:51

















                                    Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                    – Elletlar
                                    Jan 28 at 12:51





                                    Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer

                                    – Elletlar
                                    Jan 28 at 12:51











                                    0














                                    Simple and dynamic way.



                                    This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.



                                    handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });





                                    share|improve this answer






























                                      0














                                      Simple and dynamic way.



                                      This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.



                                      handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });





                                      share|improve this answer




























                                        0












                                        0








                                        0







                                        Simple and dynamic way.



                                        This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.



                                        handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });





                                        share|improve this answer















                                        Simple and dynamic way.



                                        This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.



                                        handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Mar 30 at 22:44

























                                        answered Mar 30 at 22:39









                                        Alejandro Sánchez DuránAlejandro Sánchez Durán

                                        214




                                        214























                                            -1














                                            You can try with this:



                                            this.setState(prevState => {
                                            prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                            prevState.name = 'someOtherName';
                                            return {jasper: prevState}
                                            })


                                            or for other property:



                                            this.setState(prevState => {
                                            prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                            prevState.age = 'someOtherAge';
                                            return {jasper: prevState}
                                            })


                                            Or you can use handleChage function:



                                            handleChage(event) {
                                            const {name, value} = event.target;
                                            this.setState(prevState => {
                                            prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                            prevState[name] = value;
                                            return {jasper: prevState}
                                            })
                                            }


                                            and HTML code:



                                            <input 
                                            type={"text"}
                                            name={"name"}
                                            value={this.state.jasper.name}
                                            onChange={this.handleChange}
                                            />
                                            <br/>
                                            <input
                                            type={"text"}
                                            name={"age"}
                                            value={this.state.jasper.age}
                                            onChange={this.handleChange}
                                            />





                                            share|improve this answer






























                                              -1














                                              You can try with this:



                                              this.setState(prevState => {
                                              prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                              prevState.name = 'someOtherName';
                                              return {jasper: prevState}
                                              })


                                              or for other property:



                                              this.setState(prevState => {
                                              prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                              prevState.age = 'someOtherAge';
                                              return {jasper: prevState}
                                              })


                                              Or you can use handleChage function:



                                              handleChage(event) {
                                              const {name, value} = event.target;
                                              this.setState(prevState => {
                                              prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                              prevState[name] = value;
                                              return {jasper: prevState}
                                              })
                                              }


                                              and HTML code:



                                              <input 
                                              type={"text"}
                                              name={"name"}
                                              value={this.state.jasper.name}
                                              onChange={this.handleChange}
                                              />
                                              <br/>
                                              <input
                                              type={"text"}
                                              name={"age"}
                                              value={this.state.jasper.age}
                                              onChange={this.handleChange}
                                              />





                                              share|improve this answer




























                                                -1












                                                -1








                                                -1







                                                You can try with this:



                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState.name = 'someOtherName';
                                                return {jasper: prevState}
                                                })


                                                or for other property:



                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState.age = 'someOtherAge';
                                                return {jasper: prevState}
                                                })


                                                Or you can use handleChage function:



                                                handleChage(event) {
                                                const {name, value} = event.target;
                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState[name] = value;
                                                return {jasper: prevState}
                                                })
                                                }


                                                and HTML code:



                                                <input 
                                                type={"text"}
                                                name={"name"}
                                                value={this.state.jasper.name}
                                                onChange={this.handleChange}
                                                />
                                                <br/>
                                                <input
                                                type={"text"}
                                                name={"age"}
                                                value={this.state.jasper.age}
                                                onChange={this.handleChange}
                                                />





                                                share|improve this answer















                                                You can try with this:



                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState.name = 'someOtherName';
                                                return {jasper: prevState}
                                                })


                                                or for other property:



                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState.age = 'someOtherAge';
                                                return {jasper: prevState}
                                                })


                                                Or you can use handleChage function:



                                                handleChage(event) {
                                                const {name, value} = event.target;
                                                this.setState(prevState => {
                                                prevState = JSON.parse(JSON.stringify(this.state.jasper));
                                                prevState[name] = value;
                                                return {jasper: prevState}
                                                })
                                                }


                                                and HTML code:



                                                <input 
                                                type={"text"}
                                                name={"name"}
                                                value={this.state.jasper.name}
                                                onChange={this.handleChange}
                                                />
                                                <br/>
                                                <input
                                                type={"text"}
                                                name={"age"}
                                                value={this.state.jasper.age}
                                                onChange={this.handleChange}
                                                />






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jan 3 at 13:00

























                                                answered Jan 3 at 12:46









                                                Nemanja StojanovicNemanja Stojanovic

                                                65




                                                65

















                                                    protected by Community Mar 14 at 18:31



                                                    Thank you for your interest in this question.
                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                    Would you like to answer one of these unanswered questions instead?



                                                    Popular posts from this blog

                                                    'app-layout' is not a known element: how to share Component with different Modules

                                                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                                                    WPF add header to Image with URL pettitions [duplicate]