Skip to content
Advertisement

useState executing before another function

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
}

Advertisement

Answer

From your question, it is not clear if you are converting the response to json by invoking .json() on the API response. Maybe you are doing that in login(). Please share the code for login and console.log() output of respond.

My suggestion would be to remove await from within the then() promise handler. That function would only be invoked once the response is available. You could restructure you axios call and response handling as per the accepted answer here Axios response restructuring

I do not see any other issue with your code. It would be very helpful if you could create a sample app to further debug the problem.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement