REDUX - How to import an API function returning Promise and add it into payload on action creator

江枫思渺然 提交于 2019-12-25 03:22:21

问题


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



来源:https://stackoverflow.com/questions/51575095/redux-how-to-import-an-api-function-returning-promise-and-add-it-into-payload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!