Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

javascript - How can we store a prevState data in to a variable so that if any error occurs during api call we can revert the change that took place

I have a toggle button which toggles data after click after which api is called to make necessary changes in databases. So if api ends up with error I wish to revert the changes that took place in UI. How can I achieve this.

currently trying to do like this

#global variable
let prevData={}

#Set State
(data)=>{ 
this.setState(prevState=>{
this.prevData=prevState.data
return {
data:data
}}}

this if I console log prevData its gives the updated state data instead of prevData

question from:https://stackoverflow.com/questions/65918254/how-can-we-store-a-prevstate-data-in-to-a-variable-so-that-if-any-error-occurs-d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After some searching found that

JSON object can create a detached copy of an object, which then wont change the data as the state changes.

this.prevData=JSON.parse(JSON.stringify(this.state.data)) 

There are multiple ways of creating copies this seems easier to understand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...