I create app.get to return token from Spotify
here is the code :
axios({
url: "https://accounts.spotify.com/api/token",
method: "POST",
headers: {
Authorization:
"Basic " +
Buffer.from(clientId + ":" + clientSecret).toString("base64"),
"Content-Type": "application/x-www-form-urlencoded",
},
params: {
grant_type: "refresh_token",
refresh_token: refreshToken,
},
})
.then((response) => {
res.json({
accessToken: response.data.access_token,
expiresIn: response.data.expires_in,
});
})
.catch((error) => console.log(error.statusCode));
});
and a function on the client-side whenever I call, it will return the token but when I console log the code below, it prints out non-stop
here the code:
let getData = () => {
axios.request("http://localhost:3001/refresh_token").then((response) => {
SetToken(response.data);
setExpires(response.data.expiresIn);
console.log(token);
});
};
useEffect(() => {
const data = setInterval(() => {
getData();
}, 1000);
});
return (
<div className="spotify">
<button
onClick={() => {
getData();
}}
>
click
</button>
</div>
);
thank you
Your useEffect
is missing a dependency array, so it will be called for every rerender of your component (and even worse, it will create a new interval timeout that's never cleared every time). I'll bravely assume setToken
and setExpires
are state setters for the component, so those would cause rerenders.
You'll need
useEffect(() => {
const dataTimer = setInterval(() => {
getData();
}, 1000);
return () => clearInterval(dataTimer);
}, []); // <- this empty dependency array
so it will only be called once when your component mounts, and so the interval is cleaned up when it unmounts.
(getData
should also be in that dependency array, but since you're not seemingly memoizing it using useCallback
, that would negate the benefit of the empty array, since the identity of getData
would also be changing on each render...)