Home > database >  Axios requests function returning a response as a promise however when consoled its showing undefine
Axios requests function returning a response as a promise however when consoled its showing undefine

Time:08-11

I have written a centralized function to handle all axios requests which is as follows :

export async function callApi(apiOptions) {
  let headers = {
    'X-Client-ID': '********************',  //using * for security purposes
    'X-Client-Secret': '******************', //same
  };
  if (apiOptions.headers !== undefined) {
    apiOptions.headers.forEach(header => {
      headers[header.name] = header.value;
    });
  }
  let options = {};
  options = {
    url: apiOptions.endpoint,
    method: apiOptions.method,
    baseURL: process.env.REACT_APP_API_BASE_URL,
    headers: headers,
    data: apiOptions.data,
  };
  await axios(options)
    .then(response => {
      console.log(response); //200 status code
      return response;
    })
    .catch(error => {
      return error;
    });
}

The function accepts an 'options' object and sends an axios request accordingly which then return the response to the caller. However, when I call the function and log the response it shows 'undefined'.

useEffect(() => {
    let options = {
      endpoint: '/password-policy',
      method: 'GET',
    };
    callApi(options)
      .then(response => {
        console.log('RES', response); // consoles 'undefined'
      })
      .catch(err => {
        console.log('err', err);
      });
  }, [width]);

Can someone please show where I am going wrong. Thanks a ton in advance.

CodePudding user response:

You need to return in callApi:

  return await axios(options)
    .then(response => {
      console.log(response); //200 status code
      return response;
    })
    .catch(error => {
      return error;
    });

That said, it's not great to mix callbacks and async and await, you can simplify it:

export async function callApi(apiOptions) {
  let headers = {
    'X-Client-ID': '********************',  //using * for security purposes
    'X-Client-Secret': '******************', //same
  };
  if (apiOptions.headers !== undefined) {
    apiOptions.headers.forEach(header => {
      headers[header.name] = header.value;
    });
  }
  let options = {};
  options = {
    url: apiOptions.endpoint,
    method: apiOptions.method,
    baseURL: process.env.REACT_APP_API_BASE_URL,
    headers: headers,
    data: apiOptions.data,
  };

  const response = await axios(options)
  console.log(response); //200 status code
  return response;
}
  • Related