0

I need to persist step form's data as if the user clicks on other step. So during unmounting of step form component, I need to update the state to REDUX store

Issue

The state seems to be resetting to default as soon as I am accessing it while unmounting;

// local state 
  const [state, setState] = React.useState({
    named: [{ id: uuid(), value: '', name: '', type: ' ' }], //  initial state
  });

  React.useEffect(() => {
    // update redux state before unmounting
    return () => {
      //  sets itself to initial state ignoring what user has typed
      console.log(state); // prints [{ id: uuid(), value: '', name: '', type: ' ' }]       
      updateStepThreeReduxState(state); // redux action
    };
  }, []);

Is there any way we can get an access to the state just before unmouting ??

Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • See https://stackoverflow.com/questions/60456803/how-to-access-state-when-component-unmount-with-react-hooks – Shivam Jha Jul 29 '21 at 07:00

1 Answers1

1

State and updateStepThreeReduxState are dependencies of your effect:

//custom hook defined outside the component
function useIsMounted() {
  const isMounted = useRef(false)
  useEffect(() => {
    isMounted.current = true
    return () => {
      isMounted.current = false
    }
  }, [])
  return () => isMounted.current
}

// local state
const [state, setState] = React.useState({
  named: [{ id: uuid(), value: '', name: '', type: ' ' }], //  initial state
});
const mounted = useIsMounted()
React.useEffect(() => {
  // update redux state before unmounting
  return () => {
    if(!mounted()){
      console.log(state); // prints [{ id: uuid(), value: '', name: '', type: ' ' }]
      updateStepThreeReduxState(state); // redux action
    }
  };
}, [state, updateStepThreeReduxState,mounted]);//<- added dependencies

Because you didn't add it to dependencies you have a state value that is a stale closure. Missing dependencies should cause a warning with the linter, create react app should have set all of this up for you so either use create-react-app or stop ignoring the warnings it produces.

HMR
  • 37,593
  • 24
  • 91
  • 160