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;
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
add a comment |
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
add a comment |
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
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
javascript reactjs
edited Jan 18 '16 at 13:41
Felix Kling
565k132873942
565k132873942
asked Jan 18 '16 at 0:43
GuyGuy
7,18142444
7,18142444
add a comment |
add a comment |
11 Answers
11
active
oldest
votes
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()
.
1
This is the method I use. I do want to comment thatreplaceState
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 thatreplaceState()
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 thatsetState
merges the state. If component adds fields to state that are not ininitialState
, 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 changestate
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate
– RaptoX
Dec 15 '17 at 14:11
|
show 6 more comments
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.
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 anObject.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
add a comment |
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());
With this option, I don't need to make a deep copy.
– PedroHidalgo
Jan 16 at 2:14
add a comment |
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 )
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
add a comment |
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)
objects are passed as reference, so this wont work.
– Goran Jakovljevic
Dec 26 '18 at 15:53
add a comment |
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.
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 dothis.state = initialState;
– vanegeek
Aug 7 '18 at 15:44
add a comment |
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
add a comment |
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.
1
Wouldn'tthis._initState
be undefined in your constructor? Did you meanthis.state = this._initialState
?
– chrisjlee
Mar 8 '17 at 20:24
Yup. thanks @chrisjlee it was a typo.
– eveevans
Aug 21 '17 at 18:49
add a comment |
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.
add a comment |
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.
add a comment |
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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()
.
1
This is the method I use. I do want to comment thatreplaceState
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 thatreplaceState()
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 thatsetState
merges the state. If component adds fields to state that are not ininitialState
, 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 changestate
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate
– RaptoX
Dec 15 '17 at 14:11
|
show 6 more comments
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()
.
1
This is the method I use. I do want to comment thatreplaceState
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 thatreplaceState()
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 thatsetState
merges the state. If component adds fields to state that are not ininitialState
, 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 changestate
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate
– RaptoX
Dec 15 '17 at 14:11
|
show 6 more comments
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()
.
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()
.
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 thatreplaceState
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 thatreplaceState()
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 thatsetState
merges the state. If component adds fields to state that are not ininitialState
, 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 changestate
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate
– RaptoX
Dec 15 '17 at 14:11
|
show 6 more comments
1
This is the method I use. I do want to comment thatreplaceState
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 thatreplaceState()
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 thatsetState
merges the state. If component adds fields to state that are not ininitialState
, 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 changestate
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate
– 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
|
show 6 more comments
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.
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 anObject.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
add a comment |
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.
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 anObject.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
add a comment |
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.
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.
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 anObject.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
add a comment |
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 anObject.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
add a comment |
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());
With this option, I don't need to make a deep copy.
– PedroHidalgo
Jan 16 at 2:14
add a comment |
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());
With this option, I don't need to make a deep copy.
– PedroHidalgo
Jan 16 at 2:14
add a comment |
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());
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());
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
add a comment |
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
add a comment |
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 )
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
add a comment |
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 )
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
add a comment |
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 )
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 )
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
add a comment |
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
add a comment |
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)
objects are passed as reference, so this wont work.
– Goran Jakovljevic
Dec 26 '18 at 15:53
add a comment |
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)
objects are passed as reference, so this wont work.
– Goran Jakovljevic
Dec 26 '18 at 15:53
add a comment |
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)
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)
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
add a comment |
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
add a comment |
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.
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 dothis.state = initialState;
– vanegeek
Aug 7 '18 at 15:44
add a comment |
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.
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 dothis.state = initialState;
– vanegeek
Aug 7 '18 at 15:44
add a comment |
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.
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.
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 dothis.state = initialState;
– vanegeek
Aug 7 '18 at 15:44
add a comment |
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 dothis.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
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Nov 2 '18 at 20:10
answered Nov 2 '18 at 18:40
uke5taruke5tar
463
463
add a comment |
add a comment |
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.
1
Wouldn'tthis._initState
be undefined in your constructor? Did you meanthis.state = this._initialState
?
– chrisjlee
Mar 8 '17 at 20:24
Yup. thanks @chrisjlee it was a typo.
– eveevans
Aug 21 '17 at 18:49
add a comment |
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.
1
Wouldn'tthis._initState
be undefined in your constructor? Did you meanthis.state = this._initialState
?
– chrisjlee
Mar 8 '17 at 20:24
Yup. thanks @chrisjlee it was a typo.
– eveevans
Aug 21 '17 at 18:49
add a comment |
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.
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.
edited Mar 9 at 0:54
answered Nov 30 '16 at 1:56
eveevanseveevans
3,38122335
3,38122335
1
Wouldn'tthis._initState
be undefined in your constructor? Did you meanthis.state = this._initialState
?
– chrisjlee
Mar 8 '17 at 20:24
Yup. thanks @chrisjlee it was a typo.
– eveevans
Aug 21 '17 at 18:49
add a comment |
1
Wouldn'tthis._initState
be undefined in your constructor? Did you meanthis.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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Dec 26 '18 at 16:11
Goran JakovljevicGoran Jakovljevic
1,5111618
1,5111618
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Feb 21 at 13:36
SColvinSColvin
3,03412238
3,03412238
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Oct 19 '18 at 16:06
user3065781user3065781
115
115
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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