Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to dispatch function when react component is unmount ? (React functional componet)

Tags:

Hi I'm making some function which call api and save that value in the state, and then it should dispatch when user leave the component. so I tried to use react useEffect hooks as componentWillUnmount and dispatch some action with argument as state value. but the problem is dispatch action is work but with empty string.. I think somehow state value is deleted and then dispatch function is executed.So is there's any way that I call function with state value, when user leave the component?

const [userCheck,setUserCheck]=React.useState('')

useEffect(() => {
  
  const fetChItem='this is the function which calling api '
    setUserCheck(fetChItem);

}, []);

useEffect(() => {
  return () => {
    dispatch(saveFetchValue(userCheck));
    
  };
}, []);



like image 726
jenny Avatar asked Dec 01 '20 20:12

jenny


1 Answers

Issue

This won't work because of how enclosures work with the useEffect callback. With the following

useEffect(() => {
  return () => {
    dispatch(saveFetchValue(userCheck));
  };
}, []);

You have enclosed the initial userCheck state value ("") in the returned cleanup function.

Solution

Use a react ref and a second useEffect hook to "cache" the latest state.

const [userCheck, setUserCheck] = React.useState('');

const userCheckRef = React.useRef(userCheck); // ref to store state value

React.useEffect(() => {
  userCheckRef.current = userCheck; // save userCheck state value to ref
}, [userCheck]);

...

useEffect(() => {
  return () => {
    dispatch(saveFetchValue(userCheckRef.current)); // pass current ref value
  };
}, []);

Demo

Edit is-it-possible-to-dispatch-function-when-react-component-is-unmount-react-fun

like image 194
Drew Reese Avatar answered Sep 30 '22 14:09

Drew Reese