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

后端 未结 4 1318
执念已碎
执念已碎 2020-12-29 22:38

I\'m trying to write some test using react, redux-mock-store and redux, but I keep getting and error. Maybe because my Promise has not yet been resolved?

<
相关标签:
4条回答
  • 2020-12-29 23:01

    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

    0 讨论(0)
  • 2020-12-29 23:02

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

    0 讨论(0)
  • 2020-12-29 23:12

    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

    0 讨论(0)
  • 2020-12-29 23:20

    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 });
        });
      }
    }
    
    0 讨论(0)
提交回复
热议问题