REDUX - How to import an API function returning Pr

2019-08-28 04:15发布

问题:

My Redux is rusty to say the least, I am trying to import functions from API which returns a Promise. I want to add this Promise to the payload on action creator, but it complains that TypeError: Cannot read property 'getBetList' of undefined

Here is my action creator:

import { getBetList, getLatestPrices } from '../api/index';
export const GET_BET_LIST = 'GET_BET_LIST';
export const GET_LATEST_PRICES = 'GET_LATEST_PRICES';


export function fetchBetList() {
  const response = this.getBetList();

  return {
    type: GET_BET_LIST,
    payload: response
  }
}

export function fetchLatestPrices() {
  const response = this.getLatestPrices();

  return {
    type: GET_LATEST_PRICES,
    payload: response
  }
}

I assumed that Promise received from API will be available on payload, will flow through redux-promise and in the end I get data I need, but it stops with an error that it cannot read getBetList? where did I do a wrong on import here?

回答1:

You should use getBetList & getLatestPrices directly since you imported it on a top of the file. Remove this from the line below will fix your error.

const response = this.getBetList();
                 ^^^^

And same here

const response = this.getLatestPrices();

Btw it won't work either you should use async flow for that like so:

export function fetchLatestPrices() {
  return (dispatch) => {
    getLatestPrices()
      .then(response => dispatch({type: GET_LATEST_PRICES, payload: response}));

  }
}

More information about async actions



标签: redux