How to use the response from Axios on Client side

·

1 min read

While I was trying to use Axios today to POST some data to a HubSpot API, I encountered an undefined error.

Let me explain.

While using Axios & receiving its response in .then() I am able to see my API response successfully when viewed in the console. However, when I return the response to my UI logic, I see the same response now undefined. There might be other methods, but this one helped me:

  const onSubmit = async (data: any) => {
    try {
      let response = await submitFormDetails(data);
      console.log('response', response); //this response can be used for
      // any UI-related logic.
    } catch (err) {
      console.log(err);
    }
  }
  export const submitFormDetails = async (data: any) => {
    console.log('API running...');
    const config = { //contains API URL, payload data etc// }

    let result;
    await axios(config).then((res) => {
        console.log('API then...', res);
        result = res;
      })
      .catch( ... )
    return result;
  }

This is the desired sequence that you can see in the console:

API running ...
API then ... { the response from Backend }
API in UI ... { the response returned from the submitFormDetails API function originally received from the Backend}