I have a login component that talks with a backend to obtain a JWT token to be stored in localStorage
. The API is successfully responding with the JWT but nothing is being stored in the localStorage
. The code for onSubmit button in my component is provided below.
const onSubmit = (e) => {
e.preventDefault();
auth.login(() => {
let roles = new Set();
// As every user is a normal user
roles.add({ role: "NORMAL_USER" });
roles.add({ role: userType });
let payload = {
userName: email,
password: password,
roles: Array.from(roles),
};
axios
.post(`${process.env.REACT_APP_API_URL}/login`, payload)
.then((res) => {
var info = {
email: email,
type: userType,
jwt: res.data.jwt,
};
localStorage.setItem("info", JSON.stringify(info));
if (userType === "NORMAL_USER") history.push("/usage");
else if (userType === "RESEARCHER") history.push("/research");
})
.catch((error) => {
if (error.response) {
setShowError(true);
setErrorMessage(error.response.data.detail);
} else {
setShowError(true);
setErrorMessage("Server Error");
}
clearForm();
});
});
};
The definition of auth.login() can be found as under:
class Auth{
constructor(){
this.authenticated = false;
}
login(callback){
this.authenticated = true;
callback();
}
logout(callback){
this.authenticated = false;
callback();
}
isAuthenticated(){
return this.isAuthenticated;
}
}
export default new Auth();
Kindly let me know in comments if more information is required.