Clearing state es6 React Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!React how to delete properties from stateHow do you reset state when keys are not known? (i.e. dynamic forms)How do I find out which DOM element has the focus?How can I select an element by name with jQuery?How to print a number with commas as thousands separators in JavaScriptHow to decide when to use Node.js?What is the purpose of Node.js module.exports and how do you use it?How to access the correct `this` inside a callback?Loop inside React JSXReactJS - Does render get called any time “setState” is called?Programmatically navigate using react routerWhy es6 react component works only with “export default”?

Was the pager message from Nick Fury to Captain Marvel unnecessary?

In musical terms, what properties are varied by the human voice to produce different words / syllables?

Inverse square law not accurate for non-point masses?

malloc in main() or malloc in another function: allocating memory for a struct and its members

By what mechanism was the 2017 UK General Election called?

Did John Wesley plagiarize Matthew Henry...?

How to ask rejected full-time candidates to apply to teach individual courses?

What is a more techy Technical Writer job title that isn't cutesy or confusing?

Marquee sign letters

Where and when has Thucydides been studied?

Where did Ptolemy compare the Earth to the distance of fixed stars?

Why is there so little support for joining EFTA in the British parliament?

Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?

New Order #6: Easter Egg

Pointing to problems without suggesting solutions

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Is this Kuo-toa homebrew race balanced?

Diophantine equation 3^a+1=3^b+5^c

Weaponising the Grasp-at-a-Distance spell

Why are current probes so expensive?

Keep at all times, the minus sign above aligned with minus sign below

Problem with display of presentation

How to achieve cat-like agility?

When does a function NOT have an antiderivative?



Clearing state es6 React



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!React how to delete properties from stateHow do you reset state when keys are not known? (i.e. dynamic forms)How do I find out which DOM element has the focus?How can I select an element by name with jQuery?How to print a number with commas as thousands separators in JavaScriptHow to decide when to use Node.js?What is the purpose of Node.js module.exports and how do you use it?How to access the correct `this` inside a callback?Loop inside React JSXReactJS - Does render get called any time “setState” is called?Programmatically navigate using react routerWhy es6 react component works only with “export default”?



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








42















I am trying to clear a components state but can't find a reference for the es6 syntax. I was using:



this.replaceState(this.getInitialState());



however this does not work with the es6 class syntax.



How would I achieve the same result?










share|improve this question






























    42















    I am trying to clear a components state but can't find a reference for the es6 syntax. I was using:



    this.replaceState(this.getInitialState());



    however this does not work with the es6 class syntax.



    How would I achieve the same result?










    share|improve this question


























      42












      42








      42


      14






      I am trying to clear a components state but can't find a reference for the es6 syntax. I was using:



      this.replaceState(this.getInitialState());



      however this does not work with the es6 class syntax.



      How would I achieve the same result?










      share|improve this question
















      I am trying to clear a components state but can't find a reference for the es6 syntax. I was using:



      this.replaceState(this.getInitialState());



      however this does not work with the es6 class syntax.



      How would I achieve the same result?







      javascript reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 18 '16 at 13:41









      Felix Kling

      565k132873942




      565k132873942










      asked Jan 18 '16 at 0:43









      GuyGuy

      7,18142444




      7,18142444






















          11 Answers
          11






          active

          oldest

          votes


















          73














          To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.



          const initialState = 
          /* etc */
          ;

          class MyComponent extends Component
          constructor(props)
          super(props)
          this.state = initialState;

          reset()
          this.setState(initialState);

          /* etc */



          Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)



          Finally, I'd recommend you use setState() and not replaceState().






          share|improve this answer


















          • 1





            This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

            – rossipedia
            Jan 18 '16 at 3:37






          • 3





            Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

            – David L. Walsh
            Jan 18 '16 at 4:06







          • 4





            Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

            – Veikko Karsikko
            Jul 6 '17 at 10:04







          • 6





            If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

            – David L. Walsh
            Jul 7 '17 at 2:08






          • 5





            this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

            – RaptoX
            Dec 15 '17 at 14:11



















          32














          Problem



          The accepted answer:



          const initialState = 
          /* etc */
          ;

          class MyComponent extends Component
          constructor(props)
          super(props)
          this.state = initialState;

          reset()
          this.setState(initialState);

          /* etc */



          unfortunately is not correct.



          initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.



          Solution



          You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.






          share|improve this answer

























          • You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

            – eveevans
            Feb 10 '18 at 4:38






          • 6





            Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

            – Aral Roca
            Mar 12 '18 at 15:46











          • This should be the accepted answer

            – Kevin Bruccoleri
            Aug 21 '18 at 23:15











          • If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

            – Bobort
            Feb 25 at 21:50



















          19














          This is the solution implemented as a function:



          Class MyComponent extends React.Component 
          constructor(props)
          super(props);
          this.state = this.getInitialState();


          getInitialState = () =>
          const initialState =
          /* state props */
          ;
          return initialState;


          resetState = () =>
          this.setState(this.getInitialState());







          share|improve this answer

























          • With this option, I don't need to make a deep copy.

            – PedroHidalgo
            Jan 16 at 2:14


















          9














          The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:



           const initialState = example: 'example' 
          ...
          constructor()
          super()
          this.state = initialState

          ...
          reset()
          const keys = Object.keys(this.state)
          const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: undefined ), )
          this.setState( ...stateReset, ...initialState )






          share|improve this answer























          • variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

            – Dr.Tranquility
            Feb 26 '18 at 16:14



















          5














          First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:



          componentWillMount() 
          this.initialState = this.state



          This stores your initial state and can be used to reset the state whenever you need by calling



          this.setState(this.initialState)





          share|improve this answer

























          • objects are passed as reference, so this wont work.

            – Goran Jakovljevic
            Dec 26 '18 at 15:53


















          3














          I will add to the above answer that the reset function should also assign state like so:



          reset() 
          this.state = initialState;
          this.setState(initialState);



          The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState() after the assignment.






          share|improve this answer


















          • 1





            This seems like overkill. Is this really the way one should do this?

            – chrisjlee
            Mar 9 '17 at 5:32






          • 1





            You are mutating state outside of the React lifecycle... This is incorrect React.

            – Shadowfool
            Sep 28 '17 at 14:12












          • You should not do this.state = initialState;

            – vanegeek
            Aug 7 '18 at 15:44


















          3














          const initialState = 
          a: '',
          b: '',
          c: ''
          ;

          class ExampleComponent extends Component
          state = ...initialState // use spread operator to avoid mutation
          handleReset = this.handleReset.bind(this);

          handleReset()
          this.setState(initialState);




          Remember that in order to be able to reset the state it is important not to mutate initialState.



          state = ...initialState // GOOD 
          // => state points to a new obj in memory which has the values of initialState

          state = initialState // BAD
          // => they point to the same obj in memory


          The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.



          state = Object.assign(, initialState); // GOOD
          state = ...initialState; // GOOD





          share|improve this answer
































            2














            This is how I handle it:



            class MyComponent extends React.Component
            constructor(props)
            super(props);
            this._initState =
            a: 1,
            b: 2

            this.state = this._initState;


            _resetState()
            this.setState(this._initState);




            Update:
            Actually this is wrong. For future readers please refer to @RaptoX answer.
            Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.






            share|improve this answer




















            • 1





              Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

              – chrisjlee
              Mar 8 '17 at 20:24












            • Yup. thanks @chrisjlee it was a typo.

              – eveevans
              Aug 21 '17 at 18:49


















            0














            In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.



            So, inside constructor you would have:



             class MyComponent extends Component 
            constructor(props)
            super(props)
            this.state =
            key: value,
            key2: value

            this.initialState = ...this.state




            From there you can use



            this.setState(this.initialState);


            to reset. But if for some reason your initial state is more complex object, use some library.






            share|improve this answer






























              0














              In some circumstances, it's sufficient to just set all values of state to null.



              If you're state is updated in such a way, that you don't know what might be in there, you might want to use



              this.setState(Object.assign(...Object.keys(this.state).map(k => ([k]: null))))


              Which will change the state as follows



              foo: 1, bar: 2, spam: "whatever" > foo: null, bar: null, spam: null


              Not a solution in all cases, but works well for me.






              share|improve this answer






























                -1














                class x extends Components {
                constructor()
                super();
                this.state =

                name: 'mark',
                age: 32,
                isAdmin: true,
                hits: 0,

                // since this.state is an object
                // simply add a method..

                resetSelectively()
                //i don't want to reset both name and age
                // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
                // it will assume the values in default..
                // this.name = this.name; //which means the current state.
                // this.age = this.age;


                // do reset isAdmin and hits(suppose this.state.hits is 100 now)

                isAdmin = false;
                hits = 0;
                // resetSelectively..

                //constructor..

                /* now from any function i can just call */
                myfunction()
                /**
                * this function code..
                */
                resetValues();

                // myfunction..

                resetValues()
                this.state.resetSelectively();
                //resetValues

                /////
                //finally you can reset the values in constructor selectively at any point

                ...rest of the class..

                //class





                share|improve this answer























                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34845650%2fclearing-state-es6-react%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  11 Answers
                  11






                  active

                  oldest

                  votes








                  11 Answers
                  11






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  73














                  To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)



                  Finally, I'd recommend you use setState() and not replaceState().






                  share|improve this answer


















                  • 1





                    This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                    – rossipedia
                    Jan 18 '16 at 3:37






                  • 3





                    Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                    – David L. Walsh
                    Jan 18 '16 at 4:06







                  • 4





                    Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                    – Veikko Karsikko
                    Jul 6 '17 at 10:04







                  • 6





                    If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                    – David L. Walsh
                    Jul 7 '17 at 2:08






                  • 5





                    this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                    – RaptoX
                    Dec 15 '17 at 14:11
















                  73














                  To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)



                  Finally, I'd recommend you use setState() and not replaceState().






                  share|improve this answer


















                  • 1





                    This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                    – rossipedia
                    Jan 18 '16 at 3:37






                  • 3





                    Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                    – David L. Walsh
                    Jan 18 '16 at 4:06







                  • 4





                    Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                    – Veikko Karsikko
                    Jul 6 '17 at 10:04







                  • 6





                    If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                    – David L. Walsh
                    Jul 7 '17 at 2:08






                  • 5





                    this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                    – RaptoX
                    Dec 15 '17 at 14:11














                  73












                  73








                  73







                  To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)



                  Finally, I'd recommend you use setState() and not replaceState().






                  share|improve this answer













                  To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  Beware that the line this.state = initialState; requires you never to mutate your state, otherwise you'll pollute initialState and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState in the constructor. (Or make initialState a function, as per getInitialState().)



                  Finally, I'd recommend you use setState() and not replaceState().







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 18 '16 at 1:25









                  David L. WalshDavid L. Walsh

                  14.8k44640




                  14.8k44640







                  • 1





                    This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                    – rossipedia
                    Jan 18 '16 at 3:37






                  • 3





                    Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                    – David L. Walsh
                    Jan 18 '16 at 4:06







                  • 4





                    Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                    – Veikko Karsikko
                    Jul 6 '17 at 10:04







                  • 6





                    If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                    – David L. Walsh
                    Jul 7 '17 at 2:08






                  • 5





                    this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                    – RaptoX
                    Dec 15 '17 at 14:11













                  • 1





                    This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                    – rossipedia
                    Jan 18 '16 at 3:37






                  • 3





                    Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                    – David L. Walsh
                    Jan 18 '16 at 4:06







                  • 4





                    Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                    – Veikko Karsikko
                    Jul 6 '17 at 10:04







                  • 6





                    If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                    – David L. Walsh
                    Jul 7 '17 at 2:08






                  • 5





                    this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                    – RaptoX
                    Dec 15 '17 at 14:11








                  1




                  1





                  This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                  – rossipedia
                  Jan 18 '16 at 3:37





                  This is the method I use. I do want to comment that replaceState is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.

                  – rossipedia
                  Jan 18 '16 at 3:37




                  3




                  3





                  Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                  – David L. Walsh
                  Jan 18 '16 at 4:06






                  Actually it turns out that replaceState() isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.

                  – David L. Walsh
                  Jan 18 '16 at 4:06





                  4




                  4





                  Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                  – Veikko Karsikko
                  Jul 6 '17 at 10:04






                  Be aware that setState merges the state. If component adds fields to state that are not in initialState, those will not be cleared.

                  – Veikko Karsikko
                  Jul 6 '17 at 10:04





                  6




                  6





                  If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                  – David L. Walsh
                  Jul 7 '17 at 2:08





                  If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.

                  – David L. Walsh
                  Jul 7 '17 at 2:08




                  5




                  5





                  this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                  – RaptoX
                  Dec 15 '17 at 14:11






                  this doesn't work properly, because if you change state then it also changes initialState because it was assigned by reference. So when you call reset it actually doesn't reset to initialState. Nothing changes, you have to deep copy initialState to state

                  – RaptoX
                  Dec 15 '17 at 14:11














                  32














                  Problem



                  The accepted answer:



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  unfortunately is not correct.



                  initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.



                  Solution



                  You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.






                  share|improve this answer

























                  • You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                    – eveevans
                    Feb 10 '18 at 4:38






                  • 6





                    Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                    – Aral Roca
                    Mar 12 '18 at 15:46











                  • This should be the accepted answer

                    – Kevin Bruccoleri
                    Aug 21 '18 at 23:15











                  • If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                    – Bobort
                    Feb 25 at 21:50
















                  32














                  Problem



                  The accepted answer:



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  unfortunately is not correct.



                  initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.



                  Solution



                  You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.






                  share|improve this answer

























                  • You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                    – eveevans
                    Feb 10 '18 at 4:38






                  • 6





                    Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                    – Aral Roca
                    Mar 12 '18 at 15:46











                  • This should be the accepted answer

                    – Kevin Bruccoleri
                    Aug 21 '18 at 23:15











                  • If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                    – Bobort
                    Feb 25 at 21:50














                  32












                  32








                  32







                  Problem



                  The accepted answer:



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  unfortunately is not correct.



                  initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.



                  Solution



                  You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.






                  share|improve this answer















                  Problem



                  The accepted answer:



                  const initialState = 
                  /* etc */
                  ;

                  class MyComponent extends Component
                  constructor(props)
                  super(props)
                  this.state = initialState;

                  reset()
                  this.setState(initialState);

                  /* etc */



                  unfortunately is not correct.



                  initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.



                  Solution



                  You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 15 '17 at 14:41

























                  answered Dec 15 '17 at 14:31









                  RaptoXRaptoX

                  9321913




                  9321913












                  • You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                    – eveevans
                    Feb 10 '18 at 4:38






                  • 6





                    Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                    – Aral Roca
                    Mar 12 '18 at 15:46











                  • This should be the accepted answer

                    – Kevin Bruccoleri
                    Aug 21 '18 at 23:15











                  • If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                    – Bobort
                    Feb 25 at 21:50


















                  • You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                    – eveevans
                    Feb 10 '18 at 4:38






                  • 6





                    Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                    – Aral Roca
                    Mar 12 '18 at 15:46











                  • This should be the accepted answer

                    – Kevin Bruccoleri
                    Aug 21 '18 at 23:15











                  • If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                    – Bobort
                    Feb 25 at 21:50

















                  You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                  – eveevans
                  Feb 10 '18 at 4:38





                  You are right. Also this is the reason why Immutable.js (and other immutable libraries) exists.

                  – eveevans
                  Feb 10 '18 at 4:38




                  6




                  6





                  Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                  – Aral Roca
                  Mar 12 '18 at 15:46





                  Under the hood, React is doing an Object.assign(, nextState, partialState);. So, is not necessary to do a deep copy of initialState, because this.state always is a new object after the setState. Ok, the Object.assign only clones one level... But all the saved state with the setState method should be without mutate the state, passing a new copy with the changes.

                  – Aral Roca
                  Mar 12 '18 at 15:46













                  This should be the accepted answer

                  – Kevin Bruccoleri
                  Aug 21 '18 at 23:15





                  This should be the accepted answer

                  – Kevin Bruccoleri
                  Aug 21 '18 at 23:15













                  If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                  – Bobort
                  Feb 25 at 21:50






                  If this answer was correct, I would be having an issue when I set the state to the initial state and then try to reset it again. But that is not happening at all. The users who voted on this answer do not truly understand what is going on. I'm so frustrated right now that so many people have been duped by this dubious understanding, especially since it's so easy to test.

                  – Bobort
                  Feb 25 at 21:50












                  19














                  This is the solution implemented as a function:



                  Class MyComponent extends React.Component 
                  constructor(props)
                  super(props);
                  this.state = this.getInitialState();


                  getInitialState = () =>
                  const initialState =
                  /* state props */
                  ;
                  return initialState;


                  resetState = () =>
                  this.setState(this.getInitialState());







                  share|improve this answer

























                  • With this option, I don't need to make a deep copy.

                    – PedroHidalgo
                    Jan 16 at 2:14















                  19














                  This is the solution implemented as a function:



                  Class MyComponent extends React.Component 
                  constructor(props)
                  super(props);
                  this.state = this.getInitialState();


                  getInitialState = () =>
                  const initialState =
                  /* state props */
                  ;
                  return initialState;


                  resetState = () =>
                  this.setState(this.getInitialState());







                  share|improve this answer

























                  • With this option, I don't need to make a deep copy.

                    – PedroHidalgo
                    Jan 16 at 2:14













                  19












                  19








                  19







                  This is the solution implemented as a function:



                  Class MyComponent extends React.Component 
                  constructor(props)
                  super(props);
                  this.state = this.getInitialState();


                  getInitialState = () =>
                  const initialState =
                  /* state props */
                  ;
                  return initialState;


                  resetState = () =>
                  this.setState(this.getInitialState());







                  share|improve this answer















                  This is the solution implemented as a function:



                  Class MyComponent extends React.Component 
                  constructor(props)
                  super(props);
                  this.state = this.getInitialState();


                  getInitialState = () =>
                  const initialState =
                  /* state props */
                  ;
                  return initialState;


                  resetState = () =>
                  this.setState(this.getInitialState());








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 13 '17 at 0:24









                  Unheilig

                  12.1k165587




                  12.1k165587










                  answered May 13 '17 at 0:01









                  Eruz ApodacaEruz Apodaca

                  26127




                  26127












                  • With this option, I don't need to make a deep copy.

                    – PedroHidalgo
                    Jan 16 at 2:14

















                  • With this option, I don't need to make a deep copy.

                    – PedroHidalgo
                    Jan 16 at 2:14
















                  With this option, I don't need to make a deep copy.

                  – PedroHidalgo
                  Jan 16 at 2:14





                  With this option, I don't need to make a deep copy.

                  – PedroHidalgo
                  Jan 16 at 2:14











                  9














                  The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:



                   const initialState = example: 'example' 
                  ...
                  constructor()
                  super()
                  this.state = initialState

                  ...
                  reset()
                  const keys = Object.keys(this.state)
                  const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: undefined ), )
                  this.setState( ...stateReset, ...initialState )






                  share|improve this answer























                  • variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                    – Dr.Tranquility
                    Feb 26 '18 at 16:14
















                  9














                  The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:



                   const initialState = example: 'example' 
                  ...
                  constructor()
                  super()
                  this.state = initialState

                  ...
                  reset()
                  const keys = Object.keys(this.state)
                  const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: undefined ), )
                  this.setState( ...stateReset, ...initialState )






                  share|improve this answer























                  • variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                    – Dr.Tranquility
                    Feb 26 '18 at 16:14














                  9












                  9








                  9







                  The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:



                   const initialState = example: 'example' 
                  ...
                  constructor()
                  super()
                  this.state = initialState

                  ...
                  reset()
                  const keys = Object.keys(this.state)
                  const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: undefined ), )
                  this.setState( ...stateReset, ...initialState )






                  share|improve this answer













                  The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:



                   const initialState = example: 'example' 
                  ...
                  constructor()
                  super()
                  this.state = initialState

                  ...
                  reset()
                  const keys = Object.keys(this.state)
                  const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: undefined ), )
                  this.setState( ...stateReset, ...initialState )







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '17 at 22:04









                  Charles OffenbacherCharles Offenbacher

                  1,66121930




                  1,66121930












                  • variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                    – Dr.Tranquility
                    Feb 26 '18 at 16:14


















                  • variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                    – Dr.Tranquility
                    Feb 26 '18 at 16:14

















                  variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                  – Dr.Tranquility
                  Feb 26 '18 at 16:14






                  variant for select-like state const keys = Object.keys(this.state); const stateReset = keys.reduce((acc, v) => ( ...acc, [v]: false ), ); this.setState(stateReset);

                  – Dr.Tranquility
                  Feb 26 '18 at 16:14












                  5














                  First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:



                  componentWillMount() 
                  this.initialState = this.state



                  This stores your initial state and can be used to reset the state whenever you need by calling



                  this.setState(this.initialState)





                  share|improve this answer

























                  • objects are passed as reference, so this wont work.

                    – Goran Jakovljevic
                    Dec 26 '18 at 15:53















                  5














                  First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:



                  componentWillMount() 
                  this.initialState = this.state



                  This stores your initial state and can be used to reset the state whenever you need by calling



                  this.setState(this.initialState)





                  share|improve this answer

























                  • objects are passed as reference, so this wont work.

                    – Goran Jakovljevic
                    Dec 26 '18 at 15:53













                  5












                  5








                  5







                  First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:



                  componentWillMount() 
                  this.initialState = this.state



                  This stores your initial state and can be used to reset the state whenever you need by calling



                  this.setState(this.initialState)





                  share|improve this answer















                  First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:



                  componentWillMount() 
                  this.initialState = this.state



                  This stores your initial state and can be used to reset the state whenever you need by calling



                  this.setState(this.initialState)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 12 '17 at 18:15









                  skwidbreth

                  2,59512258




                  2,59512258










                  answered Sep 8 '17 at 12:27









                  Balanced02Balanced02

                  20938




                  20938












                  • objects are passed as reference, so this wont work.

                    – Goran Jakovljevic
                    Dec 26 '18 at 15:53

















                  • objects are passed as reference, so this wont work.

                    – Goran Jakovljevic
                    Dec 26 '18 at 15:53
















                  objects are passed as reference, so this wont work.

                  – Goran Jakovljevic
                  Dec 26 '18 at 15:53





                  objects are passed as reference, so this wont work.

                  – Goran Jakovljevic
                  Dec 26 '18 at 15:53











                  3














                  I will add to the above answer that the reset function should also assign state like so:



                  reset() 
                  this.state = initialState;
                  this.setState(initialState);



                  The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState() after the assignment.






                  share|improve this answer


















                  • 1





                    This seems like overkill. Is this really the way one should do this?

                    – chrisjlee
                    Mar 9 '17 at 5:32






                  • 1





                    You are mutating state outside of the React lifecycle... This is incorrect React.

                    – Shadowfool
                    Sep 28 '17 at 14:12












                  • You should not do this.state = initialState;

                    – vanegeek
                    Aug 7 '18 at 15:44















                  3














                  I will add to the above answer that the reset function should also assign state like so:



                  reset() 
                  this.state = initialState;
                  this.setState(initialState);



                  The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState() after the assignment.






                  share|improve this answer


















                  • 1





                    This seems like overkill. Is this really the way one should do this?

                    – chrisjlee
                    Mar 9 '17 at 5:32






                  • 1





                    You are mutating state outside of the React lifecycle... This is incorrect React.

                    – Shadowfool
                    Sep 28 '17 at 14:12












                  • You should not do this.state = initialState;

                    – vanegeek
                    Aug 7 '18 at 15:44













                  3












                  3








                  3







                  I will add to the above answer that the reset function should also assign state like so:



                  reset() 
                  this.state = initialState;
                  this.setState(initialState);



                  The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState() after the assignment.






                  share|improve this answer













                  I will add to the above answer that the reset function should also assign state like so:



                  reset() 
                  this.state = initialState;
                  this.setState(initialState);



                  The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState() after the assignment.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 30 '16 at 16:18









                  Brian LoughnaneBrian Loughnane

                  20126




                  20126







                  • 1





                    This seems like overkill. Is this really the way one should do this?

                    – chrisjlee
                    Mar 9 '17 at 5:32






                  • 1





                    You are mutating state outside of the React lifecycle... This is incorrect React.

                    – Shadowfool
                    Sep 28 '17 at 14:12












                  • You should not do this.state = initialState;

                    – vanegeek
                    Aug 7 '18 at 15:44












                  • 1





                    This seems like overkill. Is this really the way one should do this?

                    – chrisjlee
                    Mar 9 '17 at 5:32






                  • 1





                    You are mutating state outside of the React lifecycle... This is incorrect React.

                    – Shadowfool
                    Sep 28 '17 at 14:12












                  • You should not do this.state = initialState;

                    – vanegeek
                    Aug 7 '18 at 15:44







                  1




                  1





                  This seems like overkill. Is this really the way one should do this?

                  – chrisjlee
                  Mar 9 '17 at 5:32





                  This seems like overkill. Is this really the way one should do this?

                  – chrisjlee
                  Mar 9 '17 at 5:32




                  1




                  1





                  You are mutating state outside of the React lifecycle... This is incorrect React.

                  – Shadowfool
                  Sep 28 '17 at 14:12






                  You are mutating state outside of the React lifecycle... This is incorrect React.

                  – Shadowfool
                  Sep 28 '17 at 14:12














                  You should not do this.state = initialState;

                  – vanegeek
                  Aug 7 '18 at 15:44





                  You should not do this.state = initialState;

                  – vanegeek
                  Aug 7 '18 at 15:44











                  3














                  const initialState = 
                  a: '',
                  b: '',
                  c: ''
                  ;

                  class ExampleComponent extends Component
                  state = ...initialState // use spread operator to avoid mutation
                  handleReset = this.handleReset.bind(this);

                  handleReset()
                  this.setState(initialState);




                  Remember that in order to be able to reset the state it is important not to mutate initialState.



                  state = ...initialState // GOOD 
                  // => state points to a new obj in memory which has the values of initialState

                  state = initialState // BAD
                  // => they point to the same obj in memory


                  The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.



                  state = Object.assign(, initialState); // GOOD
                  state = ...initialState; // GOOD





                  share|improve this answer





























                    3














                    const initialState = 
                    a: '',
                    b: '',
                    c: ''
                    ;

                    class ExampleComponent extends Component
                    state = ...initialState // use spread operator to avoid mutation
                    handleReset = this.handleReset.bind(this);

                    handleReset()
                    this.setState(initialState);




                    Remember that in order to be able to reset the state it is important not to mutate initialState.



                    state = ...initialState // GOOD 
                    // => state points to a new obj in memory which has the values of initialState

                    state = initialState // BAD
                    // => they point to the same obj in memory


                    The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.



                    state = Object.assign(, initialState); // GOOD
                    state = ...initialState; // GOOD





                    share|improve this answer



























                      3












                      3








                      3







                      const initialState = 
                      a: '',
                      b: '',
                      c: ''
                      ;

                      class ExampleComponent extends Component
                      state = ...initialState // use spread operator to avoid mutation
                      handleReset = this.handleReset.bind(this);

                      handleReset()
                      this.setState(initialState);




                      Remember that in order to be able to reset the state it is important not to mutate initialState.



                      state = ...initialState // GOOD 
                      // => state points to a new obj in memory which has the values of initialState

                      state = initialState // BAD
                      // => they point to the same obj in memory


                      The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.



                      state = Object.assign(, initialState); // GOOD
                      state = ...initialState; // GOOD





                      share|improve this answer















                      const initialState = 
                      a: '',
                      b: '',
                      c: ''
                      ;

                      class ExampleComponent extends Component
                      state = ...initialState // use spread operator to avoid mutation
                      handleReset = this.handleReset.bind(this);

                      handleReset()
                      this.setState(initialState);




                      Remember that in order to be able to reset the state it is important not to mutate initialState.



                      state = ...initialState // GOOD 
                      // => state points to a new obj in memory which has the values of initialState

                      state = initialState // BAD
                      // => they point to the same obj in memory


                      The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.



                      state = Object.assign(, initialState); // GOOD
                      state = ...initialState; // GOOD






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 2 '18 at 20:10

























                      answered Nov 2 '18 at 18:40









                      uke5taruke5tar

                      463




                      463





















                          2














                          This is how I handle it:



                          class MyComponent extends React.Component
                          constructor(props)
                          super(props);
                          this._initState =
                          a: 1,
                          b: 2

                          this.state = this._initState;


                          _resetState()
                          this.setState(this._initState);




                          Update:
                          Actually this is wrong. For future readers please refer to @RaptoX answer.
                          Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.






                          share|improve this answer




















                          • 1





                            Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                            – chrisjlee
                            Mar 8 '17 at 20:24












                          • Yup. thanks @chrisjlee it was a typo.

                            – eveevans
                            Aug 21 '17 at 18:49















                          2














                          This is how I handle it:



                          class MyComponent extends React.Component
                          constructor(props)
                          super(props);
                          this._initState =
                          a: 1,
                          b: 2

                          this.state = this._initState;


                          _resetState()
                          this.setState(this._initState);




                          Update:
                          Actually this is wrong. For future readers please refer to @RaptoX answer.
                          Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.






                          share|improve this answer




















                          • 1





                            Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                            – chrisjlee
                            Mar 8 '17 at 20:24












                          • Yup. thanks @chrisjlee it was a typo.

                            – eveevans
                            Aug 21 '17 at 18:49













                          2












                          2








                          2







                          This is how I handle it:



                          class MyComponent extends React.Component
                          constructor(props)
                          super(props);
                          this._initState =
                          a: 1,
                          b: 2

                          this.state = this._initState;


                          _resetState()
                          this.setState(this._initState);




                          Update:
                          Actually this is wrong. For future readers please refer to @RaptoX answer.
                          Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.






                          share|improve this answer















                          This is how I handle it:



                          class MyComponent extends React.Component
                          constructor(props)
                          super(props);
                          this._initState =
                          a: 1,
                          b: 2

                          this.state = this._initState;


                          _resetState()
                          this.setState(this._initState);




                          Update:
                          Actually this is wrong. For future readers please refer to @RaptoX answer.
                          Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 9 at 0:54

























                          answered Nov 30 '16 at 1:56









                          eveevanseveevans

                          3,38122335




                          3,38122335







                          • 1





                            Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                            – chrisjlee
                            Mar 8 '17 at 20:24












                          • Yup. thanks @chrisjlee it was a typo.

                            – eveevans
                            Aug 21 '17 at 18:49












                          • 1





                            Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                            – chrisjlee
                            Mar 8 '17 at 20:24












                          • Yup. thanks @chrisjlee it was a typo.

                            – eveevans
                            Aug 21 '17 at 18:49







                          1




                          1





                          Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                          – chrisjlee
                          Mar 8 '17 at 20:24






                          Wouldn't this._initState be undefined in your constructor? Did you mean this.state = this._initialState?

                          – chrisjlee
                          Mar 8 '17 at 20:24














                          Yup. thanks @chrisjlee it was a typo.

                          – eveevans
                          Aug 21 '17 at 18:49





                          Yup. thanks @chrisjlee it was a typo.

                          – eveevans
                          Aug 21 '17 at 18:49











                          0














                          In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.



                          So, inside constructor you would have:



                           class MyComponent extends Component 
                          constructor(props)
                          super(props)
                          this.state =
                          key: value,
                          key2: value

                          this.initialState = ...this.state




                          From there you can use



                          this.setState(this.initialState);


                          to reset. But if for some reason your initial state is more complex object, use some library.






                          share|improve this answer



























                            0














                            In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.



                            So, inside constructor you would have:



                             class MyComponent extends Component 
                            constructor(props)
                            super(props)
                            this.state =
                            key: value,
                            key2: value

                            this.initialState = ...this.state




                            From there you can use



                            this.setState(this.initialState);


                            to reset. But if for some reason your initial state is more complex object, use some library.






                            share|improve this answer

























                              0












                              0








                              0







                              In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.



                              So, inside constructor you would have:



                               class MyComponent extends Component 
                              constructor(props)
                              super(props)
                              this.state =
                              key: value,
                              key2: value

                              this.initialState = ...this.state




                              From there you can use



                              this.setState(this.initialState);


                              to reset. But if for some reason your initial state is more complex object, use some library.






                              share|improve this answer













                              In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.



                              So, inside constructor you would have:



                               class MyComponent extends Component 
                              constructor(props)
                              super(props)
                              this.state =
                              key: value,
                              key2: value

                              this.initialState = ...this.state




                              From there you can use



                              this.setState(this.initialState);


                              to reset. But if for some reason your initial state is more complex object, use some library.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 26 '18 at 16:11









                              Goran JakovljevicGoran Jakovljevic

                              1,5111618




                              1,5111618





















                                  0














                                  In some circumstances, it's sufficient to just set all values of state to null.



                                  If you're state is updated in such a way, that you don't know what might be in there, you might want to use



                                  this.setState(Object.assign(...Object.keys(this.state).map(k => ([k]: null))))


                                  Which will change the state as follows



                                  foo: 1, bar: 2, spam: "whatever" > foo: null, bar: null, spam: null


                                  Not a solution in all cases, but works well for me.






                                  share|improve this answer



























                                    0














                                    In some circumstances, it's sufficient to just set all values of state to null.



                                    If you're state is updated in such a way, that you don't know what might be in there, you might want to use



                                    this.setState(Object.assign(...Object.keys(this.state).map(k => ([k]: null))))


                                    Which will change the state as follows



                                    foo: 1, bar: 2, spam: "whatever" > foo: null, bar: null, spam: null


                                    Not a solution in all cases, but works well for me.






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      In some circumstances, it's sufficient to just set all values of state to null.



                                      If you're state is updated in such a way, that you don't know what might be in there, you might want to use



                                      this.setState(Object.assign(...Object.keys(this.state).map(k => ([k]: null))))


                                      Which will change the state as follows



                                      foo: 1, bar: 2, spam: "whatever" > foo: null, bar: null, spam: null


                                      Not a solution in all cases, but works well for me.






                                      share|improve this answer













                                      In some circumstances, it's sufficient to just set all values of state to null.



                                      If you're state is updated in such a way, that you don't know what might be in there, you might want to use



                                      this.setState(Object.assign(...Object.keys(this.state).map(k => ([k]: null))))


                                      Which will change the state as follows



                                      foo: 1, bar: 2, spam: "whatever" > foo: null, bar: null, spam: null


                                      Not a solution in all cases, but works well for me.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 21 at 13:36









                                      SColvinSColvin

                                      3,03412238




                                      3,03412238





















                                          -1














                                          class x extends Components {
                                          constructor()
                                          super();
                                          this.state =

                                          name: 'mark',
                                          age: 32,
                                          isAdmin: true,
                                          hits: 0,

                                          // since this.state is an object
                                          // simply add a method..

                                          resetSelectively()
                                          //i don't want to reset both name and age
                                          // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
                                          // it will assume the values in default..
                                          // this.name = this.name; //which means the current state.
                                          // this.age = this.age;


                                          // do reset isAdmin and hits(suppose this.state.hits is 100 now)

                                          isAdmin = false;
                                          hits = 0;
                                          // resetSelectively..

                                          //constructor..

                                          /* now from any function i can just call */
                                          myfunction()
                                          /**
                                          * this function code..
                                          */
                                          resetValues();

                                          // myfunction..

                                          resetValues()
                                          this.state.resetSelectively();
                                          //resetValues

                                          /////
                                          //finally you can reset the values in constructor selectively at any point

                                          ...rest of the class..

                                          //class





                                          share|improve this answer



























                                            -1














                                            class x extends Components {
                                            constructor()
                                            super();
                                            this.state =

                                            name: 'mark',
                                            age: 32,
                                            isAdmin: true,
                                            hits: 0,

                                            // since this.state is an object
                                            // simply add a method..

                                            resetSelectively()
                                            //i don't want to reset both name and age
                                            // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
                                            // it will assume the values in default..
                                            // this.name = this.name; //which means the current state.
                                            // this.age = this.age;


                                            // do reset isAdmin and hits(suppose this.state.hits is 100 now)

                                            isAdmin = false;
                                            hits = 0;
                                            // resetSelectively..

                                            //constructor..

                                            /* now from any function i can just call */
                                            myfunction()
                                            /**
                                            * this function code..
                                            */
                                            resetValues();

                                            // myfunction..

                                            resetValues()
                                            this.state.resetSelectively();
                                            //resetValues

                                            /////
                                            //finally you can reset the values in constructor selectively at any point

                                            ...rest of the class..

                                            //class





                                            share|improve this answer

























                                              -1












                                              -1








                                              -1







                                              class x extends Components {
                                              constructor()
                                              super();
                                              this.state =

                                              name: 'mark',
                                              age: 32,
                                              isAdmin: true,
                                              hits: 0,

                                              // since this.state is an object
                                              // simply add a method..

                                              resetSelectively()
                                              //i don't want to reset both name and age
                                              // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
                                              // it will assume the values in default..
                                              // this.name = this.name; //which means the current state.
                                              // this.age = this.age;


                                              // do reset isAdmin and hits(suppose this.state.hits is 100 now)

                                              isAdmin = false;
                                              hits = 0;
                                              // resetSelectively..

                                              //constructor..

                                              /* now from any function i can just call */
                                              myfunction()
                                              /**
                                              * this function code..
                                              */
                                              resetValues();

                                              // myfunction..

                                              resetValues()
                                              this.state.resetSelectively();
                                              //resetValues

                                              /////
                                              //finally you can reset the values in constructor selectively at any point

                                              ...rest of the class..

                                              //class





                                              share|improve this answer













                                              class x extends Components {
                                              constructor()
                                              super();
                                              this.state =

                                              name: 'mark',
                                              age: 32,
                                              isAdmin: true,
                                              hits: 0,

                                              // since this.state is an object
                                              // simply add a method..

                                              resetSelectively()
                                              //i don't want to reset both name and age
                                              // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
                                              // it will assume the values in default..
                                              // this.name = this.name; //which means the current state.
                                              // this.age = this.age;


                                              // do reset isAdmin and hits(suppose this.state.hits is 100 now)

                                              isAdmin = false;
                                              hits = 0;
                                              // resetSelectively..

                                              //constructor..

                                              /* now from any function i can just call */
                                              myfunction()
                                              /**
                                              * this function code..
                                              */
                                              resetValues();

                                              // myfunction..

                                              resetValues()
                                              this.state.resetSelectively();
                                              //resetValues

                                              /////
                                              //finally you can reset the values in constructor selectively at any point

                                              ...rest of the class..

                                              //class






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 19 '18 at 16:06









                                              user3065781user3065781

                                              115




                                              115



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34845650%2fclearing-state-es6-react%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  1928 у кіно

                                                  Захаров Федір Захарович

                                                  Ель Греко