Ali Rehman
Ali Rehman

Reputation: 3851

Not getting returned value from async await function

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;
    });
}

Upvotes: 2

Views: 175

Answers (2)

mss
mss

Reputation: 1493

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;
    });
}

Upvotes: 2

andy mccullough
andy mccullough

Reputation: 9551

You are not returning anything from LockUnlockAccount

You need to do

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

Upvotes: 2

Related Questions