I need to post something on my API. I have this function which works correctly:
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
I want to move fetch() to another file from where i make all API calls. In that file I already have several fetch functions (with get method) and they work fine. But when I move this fetch() with post method to that file, I get an error:
TypeError: Cannot read property 'then' of undefined
My code:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
.then(res => res.json()) returns "ok" and 200. but saveAction(actionInfo) returns undefined. How come?
The function saveAction
doesn't return anything (specifically - doesn't return promise) so you can't use then
on that function:
export function saveAction(actionInfo){
fetch({
...
})
.then(res => res.json())
}
You can return the fetch
(which is a promise) and then you can use then
on that function:
export function saveAction(actionInfo){
return fetch({
...
})
.then(res => res.json())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With