5

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?

Present practice
  • 601
  • 2
  • 15
  • 27

2 Answers2

8

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())
}
Dekel
  • 60,707
  • 10
  • 101
  • 129
-1

If it may be of any help for noobs like me,make sure the return and the fetch statement are on the same line, or surround the fetch statement in parenthesis. Avoid this! it will also cause the Cannot read property 'then' of undefined error.

function fetchData(){
    return 
       fetch(url)
        .then(response => response.json())
    } 

Try this.

function fetchData(){
    return (
      fetch(url)
        .then(response => response.json()))
    } 
StackEdd
  • 624
  • 1
  • 10
  • 23
  • related to your problem: https://stackoverflow.com/questions/22185128/why-does-the-position-affects-this-javascript-code fetch isn't the only thing that putting a newline between return and its value can break. – Kevin B Nov 02 '17 at 19:12