Danielle
Danielle

Reputation: 1496

Problem calling Axios, returning data from .then arrow function is always undefined

I have the following code:

getData = async function (afgJSON) {
      console.log("step 2")
      await axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
        .then((response) => {
          console.log("step 3")
          return response.data
        })
        .catch((e) => {
          console.log("step 3")
          return e.response.data    
        })
    }

Which I call as this:

console.log("step 1")
let afgResponse = await common.getData(afgJSON);
console.log("step 4")
console.log(afgResponse)

afgResponse always is undefined, and the console.logs show the right order:

step 1

step 2

step 3

step 4

undefined

... but if I console.log response.data (.then), the response is fine.

I was reading other posts at stackoverflow about .then => with Axios but I still cant figure this out.

Thanks.

Upvotes: 0

Views: 139

Answers (2)

boubaks
boubaks

Reputation: 372

getData = async function (afgJSON) {
    try {
      const { data } = await axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
      return data
    } catch (err) {
      return err // return the data you want
    }
}

You could also return directly axios.post and check

getData = async function (afgJSON) {
      return axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
}

And in your other file =>

const { data: afgResponse } = await common.getData(afgJSON);

But you will have to handle the error in the other file

Upvotes: 0

Bad Dobby
Bad Dobby

Reputation: 871

You missed to return the result of axios call from the function "getData"

Upvotes: 2

Related Questions