I’m working on an authentication system for my React app. For this I made a hook that will fetch the user if a cookie is present. Unfortunately, I cannot catch the 400 error in any way.. I tried .catch((e) => ())
and regular try{} catch{}
.
Here’s the function that fetches the user from the session key:
const getUserBySession = async (sessionKey) => {
const loginResponse = await fetch("http://localhost:5000/user/getbysession", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
sessionKey,
}),
}).catch((error) => console.log("invalid session"));
const loginResponseJson = await loginResponse.json();
if (loginResponse.status !== 200 || loginResponseJson.error) return;
return { ...loginResponse };
};
For some reason it keeps just showing the 400 error in red in the console without catching it, meaning that it completely skips all the code below the fetch statement, which really shouldn’t happen…
I’m calling this function in my hook like:
const useAuthentication = () => {
const [userToken, setUserToken] = useCookie("token");
const [user, setUser] = useState();
useEffect(() => {
if (!user && userToken) {
console.log("found user token");
getUserBySession(userToken).then((fetchedUser) => {
if (fetchedUser) setUser(fetchedUser);
else setUserToken(undefined);
});
}
}, []);
const setUserAndSession = (user) => {
setUserToken(user.session);
setUser(user);
};
return [user, setUserAndSession];
};
This all keeps resulting in an ugly 400 console error that references the line with fetch
in it:
If someone knows any solution or other debugging steps I could take, please let me know. Thanks in advance.