3

I am using React useState to create an object in state. This is updated to an object of data after a successful API call.

I have a form that can change this state, but I also have a cancel button. How can i restore this state to its initial values (after API call) when cancel is clicked?

Should i create another state variable and store initial state there and then update my state based on that?

  const [basePosition, setBasePosition] = useState({});
  const [position, setPosition] = useState({
    id: '',
    title: '',
    description: '',
    authoredBy: '',
    createdDate: '',
    lastUpdatedBy: '',
    lastUpdateDate: '',
    sliderResponses: [],
    tileResponses: [{}],
    template: {}
  });```

Paul
  • 219
  • 1
  • 3
  • 11
  • Does this answer your question? [Reset to Initial State with React Hooks](https://stackoverflow.com/questions/54895883/reset-to-initial-state-with-react-hooks) – Bilal Akbar Jul 13 '20 at 11:54

5 Answers5

7
const initialState = {
    id: '',
    title: '',
};

const Test = () => {
    const [position, setPosition] = useState(initialState);

    return <>
        ...form
        <button onClick={() => setPosition(initialState)}>Reset</button>
    </>;
};
BananZ
  • 1,153
  • 1
  • 12
  • 22
Nikita Madeev
  • 4,284
  • 9
  • 20
  • Thanks, out of interest why does initialState have to be outside the component? – Paul Jul 16 '20 at 18:00
  • @Paul This is not necessary, but in this case, because data is static it is better to put it outside the component. Otherwise, a new object `initialState` will be created for each render (but repeat again in this case, you will not notice performance problems :) ). – Nikita Madeev Jul 16 '20 at 18:27
  • Hi @Nikita Madeev, but initialState will update once the GET request is successful and gets the post data. It will then populate that initialState object with that data.... – Paul Jul 17 '20 at 13:42
0

Don't create another state variable just to store initial state as it will cause another re render instead when your component is mounted then intialize your initial state object:

let initialState = null;

React.useEffect(() => {
  initialState = position;
},[])

When you want to reset to initial state just use:

setPosition(initialState);
Zayn
  • 741
  • 1
  • 5
  • 22
0

You need not to create another State. Just declare an initial state which will not be changed and assign it to the Position state when it is needed to be reset. EX:

import React,{useState} from 'react'

const YourComponent = () =>{
 const initialState = {
    id: '',
    title: '',
    description: '',
    authoredBy: '',
    createdDate: '',
    lastUpdatedBy: '',
    lastUpdateDate: '',
    sliderResponses: [],
    tileResponses: [{}],
    template: {}
  }
 const [basePosition, setBasePosition] = useState({});
  const [position, setPosition] = useState(initialState);
  const resetState = () =>{
     setPosition(initialState)
   }
}
Arnab
  • 936
  • 7
  • 13
0

Answer to your question if you should store initial value is Yes.

That would be the easiest way to maintain your code. So put your initial value in a constant:

const INITIAL_VALUES = {
  id: '',
  title: '',
  description: '',
  authoredBy: '',
  createdDate: '',
  lastUpdatedBy: '',
  lastUpdateDate: '',
  sliderResponses: [],
  tileResponses: [{}],
  template: {}
}

Than every time you want to use that initial object, just spread it and all is good (spread to lose reference to constant):

const [basePosition, setBasePosition] = useState({});
const [position, setPosition] = useState({...INITIAL_VALUES});

And later when you reset:

setPosition({...INITIAL_VALUES})
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
0

import React, { useState } from 'react'

// counter 

function Example3() {

    const [initial, setIncrement] = useState(0)


    const increment = () => {
        setIncrement(initial + 1)
    }
    const dincrement = () => {
        setIncrement(initial - 1)
    }


    const reset = () => {

        setIncrement(0)

    }




    return (


        <div>

            <p>{initial}</p>
            <button onClick={increment} >+</button>
            <button onClick={dincrement} >-</button>
            <button onClick={reset}>reset</button>

        </div>


    )




}


export default Example3;




amine jisung
  • 105
  • 2
  • 14