Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Promise: TypeError: Cannot read property 'then' of undefined

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?

like image 396
Present practice Avatar asked Sep 02 '17 14:09

Present practice


1 Answers

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())
}
like image 94
Dekel Avatar answered Nov 14 '22 22:11

Dekel