Cannot read property '.then' of undefined when testing async action creators with redux and react

≯℡__Kan透↙ 提交于 2019-11-30 17:17:28

store.dispatch(actions.fetchListings()) returns undefined. You can't call .then on that.

See redux-thunk code. It executes the function you return and returns that. The function you return in fetchListings returns nothing, i.e. undefined.

Try

return (dispatch) => {
    return request.then( (data) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }

After that you will still have another problem. You don't return anything inside your then, you only dispatch. That means the next then gets undefined argument

Box and Cox

I also know this is an old thread but you need to make sure you return the async action inside of your thunk.

In my thunk I needed to:

return fetch()

the async action and it worked

I know this is an old thread. But I think the issue is that your action creator is not asynchronous.

Try:

export async function fetchListings() {
  const request = axios.get('/5/index.cfm?event=stream:listings');
  return (dispatch) => {
    request.then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
}

Your action creator should return a promise as shown below:

// actions/index.js
import axios from 'axios';

import { FETCH_LISTINGS } from './types';

export function fetchListings() {
  return (dispatch) => {
    return axios.get('/5/index.cfm?event=stream:listings')
    .then(( { data } ) => {
      dispatch({ type: FETCH_LISTINGS, payload: data });
    });
  }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!