Do i need to clear the timeout when doing this code below?
I know that you need to clear it when using it in useEffect
. But do you need to clear it when you want to delay something after submitting?
let timer = null
useEffect(() => {
return () => clearTimeout(timer)
}, [])
const onSubmit = () => {
dispatch(
submitProduct({
payload,
successCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Success`,
status: "success",
});
timer = setTimeout(() => onCloseModal(), 1000);
},
errorCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Error`,
status: "error",
});
},
})
);
};
CodePudding user response:
In this case, timer is a normal variable so it will be reset to null on every render. So here you better use a ref otherwise the cleanup is useless
Here is how you can do it using a ref
:
const timer = useRef(null);
useEffect(() => {
return () => clearTimeout(timer.current)
}, [])
const onSubmit = () => {
dispatch(
submitProduct({
payload,
successCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Success`,
status: "success",
});
timer.current = setTimeout(() => onCloseModal(), 1000);
},
errorCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Error`,
status: "error",
});
},
})
);
};
CodePudding user response:
Using a ref, you don't depend on the functional component lifecycle.
Edit: oops, same answer as above. However, you should add a check if the timeoutRef is defined.
const timeoutRef = useRef();
useEffect(() => {
return () => timeoutRef.current && clearTimeout(timeoutRef.current); // To be sure it's not undefined
}, [])
const onSubmit = () => {
dispatch(
submitProduct({
payload,
successCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Success`,
status: "success",
});
timeoutRef.current = setTimeout(() => onCloseModal(), 1000);
},
errorCallback: () => {
setOpenSnackbar(true);
setSelectedDetails({
content: `Error`,
status: "error",
});
},
})
);
};