I'm learning react query and the following code is working as expecting but I have this warning message:
React Hook useEffect has missing dependencies: 'code' and 'mutate'. Either include them or remove the dependency array.eslintreact-hooks/exhaustive-deps
But if I add 'code' and 'mutate' in the dependency array I have an infinite loop.
import React, { useState, useEffect } from "react";
import { useMutation } from "react-query";
import * as api from "../api/api";
const getQuery = () => {
const queryParams = new URLSearchParams(window.location.search);
return queryParams.get("code");
};
const Authentication = () => {
const [code] = useState(getQuery());
useEffect(() => {
if (code) {
mutate.mutate(code);
}
}, []);
const auth = async () => {
window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
};
const mutate = useMutation(api.access_token, {
onSuccess: (data) => {
localStorage.setItem("isAuth", data.data.access_token);
},
});
return <button onClick={auth}>Login</button>;
};
export default Authentication;
Short explanation of what I did:
const auth = async () => {
window.location.href = `https://www.betaseries.com/authorize?client_id=${process.env.REACT_APP_API_KEY}&scope=&redirect_uri=${process.env.REACT_APP_API_URL_CALLBACK}`;
};
After a success login he is redirected to my website with a url params ?code=xxx
I catch the code and use it to call a route that will provide me his access_token
useEffect(() => {
if (code) {
mutate.mutate(code);
}
}, []);
The mutate function itself is stable, but the object returned from useMutation is not. If you destruct, you can add it to your dependency array:
const { mutate } = useMutation(…)
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