Not getting returned value from async await function

Viewed 55

I am getting undefined returned value when I press button.

<Button btnType="outline" onClick={LockUnlockAccountHandler}>
     lock client’s account
</Button>

const LockUnlockAccountHandler = async () => {
  const status = await LockUnlockAccount(detailData?.userId, detailData?.blocked ? 'UNLOCK' : 'LOCK');
  console.log(status)
  if(status){
    setDetailData({
      ...detailData,
      blocked: !detailData.blocked
    })
  }
}

Status value is undefined in above function which should be true or false from below function.

export async function LockUnlockAccount(clientID, dataVal) {
  
  var config = {
    method: 'post',
    url: endpoint.lockAccount + clientID + "/status"  + endpoint.key,
    headers: { 
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data : qs.stringify({
      'status': dataVal 
    })
  };
  axios(config)
    .then(function (response) {
      //console.log(JSON.stringify(response));
      if (response.status === 200) {
        toast('succès');
        return true;
      }
      return false;
    })
    .catch(function (error) {
      console.log(error);
      toast('error');
      return false;
    });
}
2 Answers

You are not returning anything from LockUnlockAccount

You need to do

return axios(config).then(...)

You have to returned the response from axios, which is what will be returned by the wrapping function. just add return in front of axios call.
below is your updated code

export async function LockUnlockAccount(clientID, dataVal) {
  
  var config = {
    method: 'post',
    url: endpoint.lockAccount + clientID + "/status"  + endpoint.key,
    headers: { 
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data : qs.stringify({
      'status': dataVal 
    })
  };
  return axios(config)
    .then(function (response) {
      //console.log(JSON.stringify(response));
      if (response.status === 200) {
        toast('succès');
        return true;
      }
      return false;
    })
    .catch(function (error) {
      console.log(error);
      toast('error');
      return false;
    });
}
Related