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 binations 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
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 binations 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
Share Improve this question asked Oct 16, 2019 at 23:52 KyleKyle 3038 silver badges22 bronze badges 2- 1 Can you show us an example of what you get from the console.log? – Matt Aft Commented Oct 17, 2019 at 0:21
- @MattAft This suggestion lead to me realising I had to access a chain of data.data.data, the way the promises were chained and how graphql returns the data. Thanks. – Kyle Commented Oct 17, 2019 at 0:35
1 Answer
Reset to default 5You'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))