Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks - set state to initial state

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: {}
  });```

like image 718
Paul Avatar asked Apr 25 '26 22:04

Paul


1 Answers

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

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

    return <>
        ...form
        <button onClick={() => setPosition(initialState)}>Reset</button>
    </>;
};
like image 84
Nikita Madeev Avatar answered Apr 27 '26 12:04

Nikita Madeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!