axios.post().then() not passing resolved data to callback function

Viewed 3009

When I use axios.post(...).then(data=>callback(data)) the data is not defined when I access it in the callback, however, a console log right before the data is accessed shows all the data.

I've tried all the combinations of async await that's possible. I feel like this is a way simpler problem than I'm making it.

// passed in as successCallback
const handleCreationCompleted = data => {
    console.log(data)

    // Error below ReturnedDataObject not defined
    var object = data.ReturnedDataObject

}

const createObject = async (variables, successCallback, errorCallback) => {
    ...
    await axios.post(url, form_data, {
        headers: {
    ...
        },
    }).then(res => {
        successCallback(res)
    })
    .catch((err) => {
        errorCallback(err)
    })

I should be able to access the data, which is a json object (it's fetched from a graphql api) within the successcallback

1 Answers

You're using await with then(). You should switch to one. If you use await, assign the result to a variable. You should also be passing back the data of the response and not the response itself.

const response = await axios.post(...)
callback(response.data)

If you want to use then, then it's:

axios.post(...)
.then(respone => callback(response.data))
Related