Present practice
Present practice

Reputation: 601

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?

Upvotes: 5

Views: 9261

Answers (2)

StackEdd
StackEdd

Reputation: 712

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()))
    } 

Upvotes: -1

Dekel
Dekel

Reputation: 62556

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())
}

Upvotes: 9

Related Questions