I am trying to reset an array of object but I am unable to do it without rewriting the initial value of the state again. Initial state
const [state,setState]=useState([
{name:'abc',age:24},
{name:'xyz',age:20}
])
Is there any way that I can reset the state to its initial value without the using the approach that is in the function below.
const reset =()=>{
setState([
{name:'abc',age:24},
{name:'xyz',age:20}
])
}
CodePudding user response:
simply create a const
and store it there
const initialState=[
{name:'abc',age:24},
{name:'xyz',age:20}
]
if you want to reset state than
setState(initialState)
CodePudding user response:
No there is no built-in way to reset state, but you can improve your version by creating a constant initialState and not duplicating the object:
const initialState = [
{name:'abc',age:24},
{name:'xyz',age:20}
]
...
setState(initialState);