Jose A.
Jose A.

Reputation: 553

Reset The State on React JS

Assuming that I have a variable called "NAME", that variable has a stored name, I also have this variable in my State, lets say that variable has stored 'JOSH'

this.state = {
nombre: ' '
}

I set this variable in an input value, so when i clic in a button, puts in the input value the variable "NAME", so it shows me in the input "JOSH"

If I delete a letter or the whole field by mistake, with a button of "UNDO", i should revert the changes, so when there's "JOSH" in the input, and delete 1 letter (JOS), when i clic the button UNDO, it should bring me again "JOSH".

Here my doubt is, how do I reset the state to the original value ?

I'm thinking of something like...:

this.setSate ({name}); but something fails me here that doesn't undo it

Upvotes: 0

Views: 248

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138247

When updating the state, keep track of all previous states:

 this.state = { name: '', history: [] };

 // whe  adding name:
 this.setState(({ history, name: oldName }) => ({ name, history: [...history, oldName] }));

then later you can easily restore the previous state:

this.setState(({ history }) => ({ name: history[history.length - 1] || '', history: history.slice(0, -1) }));

Upvotes: 1

Related Questions