0

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
}
Firas SCMP
  • 461
  • 4
  • 18
  • 1
    If you're using an object as an argument for `useState` make sure you're returning the same object and updating any required fields. Otherwise you're just overwriting the state with a different object. – Juan Marco Jun 23 '22 at 11:04
  • 1
    How did you understand that setRes does not work? If you did console.log(res); right after setRes() - this is expected, res should not yet be updated because state is updated asynchronously https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – Marat Jun 23 '22 at 11:20
  • what I'm trying to do is to conditional render 3 components, the first one is Admin, second one is a study performer component, and the last one is webmail. so after user enters username and password I check if auth is true or false, if true I check another property which is what component should I render. if false I stay on the login form. but the variable res is not set as the result of the respond login function so the page keeps on rendering the login – Firas SCMP Jun 23 '22 at 11:34
  • 1
    @JuanMarco quite the opposite. You shouldn't mutate objects in state directly. Replacing them with a new object or mutating a copy is the way to go. In fact, React won't even re-render the component if you call setState with the same object that's already stored – DustInComp Jun 23 '22 at 12:09
  • Your question is not clear. Do this: 1) remove **everything** that is not directly related to this problem (so start commenting out your code and see if the issue persists or not) 2) At some point you will have just a couple lines of code that show the issue 3) Post **the whole lines** showing the problem 4) Profit from a question with a reproducible example. – GACy20 Jun 23 '22 at 12:58
  • Does this answer your question? [Get response from axios with await/async](https://stackoverflow.com/questions/49661209/get-response-from-axios-with-await-async) – Trenton McKinney Jun 24 '22 at 15:40

2 Answers2

1

do that to update res state

setRes({...res, ...respond});
1

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.

Parth Tomar
  • 261
  • 2
  • 6