I am trying to setRes()
as respond which is the result for a login request but Res
is not setting
This is the function:
const [res, setRes] = useState({ auth: false, type: '', reason: '' })
const Handlelogin = async (e) => {
e.preventDefault();
const respond = await login(e)
setRes(respond)
}
respond should return an object like this :
result={auth:false, reason:"Wrong Credentials!",type:'error' };
or
result={auth:true, type:response.data.auth};
I tried console.log() for respond and the result is correct but the setRes(respond) is not working. Any ideas?
The jsx:
{res.auth === false ? <Login/> : res.type ==='admin' ? <Admin/>: res.type==='fs' ? <Fs/> : <WebMail/>}
is this the correct way to authenticate?
login code:
import axios from "axios";
let result={};
export const login=async (e)=>{
e.preventDefault();
const data={username:e.target[0].value,password:e.target[1].value}
await axios
.post("http://localhost:3001/api/Login", data)
.then(await function (response) {
if(response.data.auth===false){
return result={auth:false, reason:"Wrong Credentials!",type:'error' };
}
else if(response.data.auth==="Network Error"){
return result={auth:false,reason:"Please check your network connection!",type:'error'}
}
else if(response.data.auth==='normal'){
window.location.href=response.data.to
}
else if(response.data.auth==='admin'){
return result={auth:true, type:response.data.auth};
}
else if(response.data.auth==='fs'){
return result={auth:true, type:response.data.auth};
}
})
.catch((error)=>{
result={auth:false,reason:"Network Error"}
});
return result
}