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));
};
}, []);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With