4
votes

I am using axios to fetch data from API endpoint. I am getting error -> Possible unhandled promise rejection Type error: undefined is not a function (evaluating res.json() )

I am using react-redux and redux-thunk with react native app.

venueAction.js :

import { FETCH_VENUES } from './types';
import axios from 'axios';

export const fetchVenues = () => dispatch => {
    axios.get(`my_api_link`)
    .then( res => res.json())
    .then( venues => 
        dispatch({
            type: FETCH_VENUES,
            payload: venues
        })
    )
    .catch( error => {
        console.log(error);
    });
};

Check screenshot below:

enter image description here

2

2 Answers

5
votes

The need to call json() on the response is part of the Fetch API. Axios instead implements an XMLHttpRequest, meaning you do not need to do this.

axios.get(`my_api_link`)
  .then(venues => {
    ...
  });

Axios is a Javascript library used to make http requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. Another feature that it has over .fetch() is that it performs automatic transforms of JSON data.

If you use .fetch() there is a two-step process when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response.

Fetch vs. Axios.js for making http requests by Jason Arnold on Medium

0
votes

Okay so now you know not to write your axios code like this:

export const fetchVenues = () => dispatch => {
    axios.get(`my_api_link`)
    .then( res => res.json())
    .then( venues => 
        dispatch({
            type: FETCH_VENUES,
            payload: venues
        })
    )
    .catch( error => {
        console.log(error);
    });
}; 

Now what? Try using ES8 async/await syntax like so:

export const fetchVenues = () => async dispatch => {
      try {
        const url = 'http://api.funwithredux.com/';
        let { data } = await axios.get(url);
        dispatch({ type: FETCH_VENUES, payload: data });
        console.log(data);
      } catch (e) {
        console.log(e);
      }
    };

And as you can see you can use a try/catch statement to catch any errors if you want to and I would definitely add a console logs to ensure you are getting data back from your API endpoint as well.