There are already many answers but I couldn't use them according to my scenario in which my login component is a child component and i am using react-router-dom of 5.1.2 version currently i am using local storage to save authToken but I know it is not a good approach. Where should I save the auth token then such that whenever someone tries to hit login route manually or by button they are redirected because token was expired my route that i am currently using in app.js
<Route path={process.env.PUBLIC_URL + "/login-register"} component={(!isVerified)?LoginRegister:HomeFashion}/>
and this is the child component login
const login = async()=>{
try{
const options = {
username:username,
password:password
}
var response = await axios.post(CONFIG.url+'api/login',options)
localStorage.setItem("__user",JSON.stringify(response.data))
history.push({
pathname: '/',
// search: '?update=true', // query string
state: { // location state
user: response.data,
},
});
}catch(err){
isError(true)
}
}
React.useEffect(()=>{
if(location.state!==undefined){
setMsg(location.state.msg)
if(msg)
{
alert(msg)
}
}
},[location])
what i am doing is when i am successfully logged in i get token and user data in response form backend I store it in localStorage and redirects things according to it
what is the right way to do so?