I am implementing the spotify api into my app however as shown in the picture below the post route gets hit 2-4 times and consstantly overwrites all the data leading to errors.
Repo(in case you need it): https://github.com/kankanrr/post-route
post route hitting multiple times
const client_id = ""; // Your client id
const client_secret = ""; // Your secret
const redirect_uri = "http://localhost:3000/callback";
const [accessToken, setAccessToken] = useState("");
const [refreshToken, setRefreshToken] = useState("");
const [expiresIn, setExpiresIn] = useState("");
useEffect(() => {
const authParams = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization:
"Basic " +
new Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
body: new URLSearchParams({
grant_type: "authorization_code",
redirect_uri: redirect_uri,
code: code,
}),
};
const refreshParams = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization:
"Basic " +
new Buffer.from(client_id + ":" + client_secret).toString("base64"),
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: client_id,
}),
};
fetch("https://accounts.spotify.com/api/token", authParams)
.then((result) => result.json())
.then((data) => {
console.log(data);
if (!accessToken) {
setAccessToken(data.access_token);
}
setRefreshToken(data.refresh_token);
setExpiresIn(data.expires_in);
if (!expiresIn) {
fetch("https://accounts.spotify.com/api/token", refreshParams)
.then((res) => res.json())
.then((data) => {
setExpiresIn(data.expires_in);
setAccessToken(data.access_token);
});
}
console.log(data.access_token);
// if (accessToken) return console.log("access toke +> " + accessToken);
// else window.history.pushState({}, null, "/");
})
.catch((err) => {
console.log(err);
res.sendStatus(400);
});
}, []);
I only want this to run once so my tokens dont get overwritten. This useEffect was originally two seperate useEffects, but i merged into one to see if it would fix the problem. I tried removing react strict mode that just completely broke the app. I tried async rqs within the useeffect. Im honestly not sure what the problem is here and why its posting mulltiple times and overwriting my token data.
2
Answers
Add accessToken and refreshToken inside dependency array of useEffect hook.
I can’t comment so I will put this here.
If you are running the application in dev mode with React.StrictMode, then any re-render will trigger twice. See this post for more information.
Try running the application in preview mode with:
vite preview
and check if the problem carries over to the build.