I have a mutation which I use to login on my application. I want to rerun that login mutation every 5 minutes to check for updates to their profile. useQuery
has a pollingInterval
options but useMutation
does not.
I tried using a hook to run the mutation on an interval but that doesn't really work because the useAuth hook is used in multiple components at the same time so it ends up creating an interval for each component.
function useInterval(callback: () => any, delay: number | null) {
const savedCallback = useRef<any>();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
function useAuth(){
const [login,{data:loginData} = useMutation(gql`
...
`);
useInterval(() => login(Cookies.get(TOKEN_NAME),1000*60*5);
return login;
}
function App(){
const login = useAuth();
useEffect(() => {
login(Cookies.get(TOKEN_NAME));
},[login]);
...
}