0
votes

I'm trying to test redux-thunk to make async calls, I've created 3 actions (request, success, failed) and create a thunk method to return the dispatched action accordingly.

import { createReducer, createActions } from "reduxsauce";
import Immutable from "seamless-immutable";
import api from "../Services/FixtureApi";

export const INITIAL_STATE = Immutable({
  Data1: [],
  loadingData: false,
  error: null
});

const { Types, Creators } = createActions({
  requestData1: null,
  receiveData1: null,
  failedData1: null
});

export const ExampleTypes = Types;
export default Creators;

export function getData() {
  return dispatch => {
    dispatch(requestData1());
    var promise = new Promise((resolve, reject) => {
      const param1 = "";
      setTimeout(() => {
        resolve(api.getData(param1));
      }, 2000);
    });

    return promise
      .then(res => {
        dispatch(receiveData1(res.data));
      })
      .catch(err => {
        dispatch(failedData1(err.message));
      });
  };
}

export const requestData1 = state => ({
  ...state,
  loadingData: true
});
export const receiveData1 = (state, action) => ({
  ...state,
  Data1: [...state.Data1, ...action.payload],
  loadingData: false
});

export const failedData1 = (state, action) => ({
  ...state,
  loadingData: false,
  error: action.payload
});

export const reducer = createReducer(INITIAL_STATE, {
  [Types.REQUEST_DATA1]: requestData1,
  [Types.RECEIVE_DATA1]: receiveData1,
  [Types.FAILED_DATA1]: failedData1
});

in my component, I connect the getData action like this

const mapDispatchToProps = dispatch => ({
  fetchData1: () => dispatch(getData())
});

running this cause the following error

enter image description here

2

2 Answers

0
votes

You need an ActionTypes.js file that declares all of your action types. For example,

export const ADD_FAVORITE = 'ADD_FAVORITE';

Then in your ActionCreators.js file, you reference the ActionTypes.

import * as ActionTypes from './ActionTypes';

export const postFavorite = (dishId)  => (dispatch) => {
     dispatch(addFavorite(dishId));    
};
export const addFavorite = (dishId) => ({
    type: ActionTypes.ADD_FAVORITE,
    payload: dishId
});

In my component, I'm going to invoke postFavorite at a button onPress event. Hope this example helps.

0
votes

I should dispatch the action from action creators object returned by reduxsauce. so the right call should be like this

export function getData() {
  return async dispatch => {
    dispatch(Creators.requestData1());
    var promise = new Promise((resolve, reject) => {
      const param1 = "";
      setTimeout(() => {
        resolve(api.getData(param1));
      }, 2000);
    });

    try {
      const res = await promise;
      if (!res.ok) throw new Error(res.error);
      dispatch(Creators.receiveData1(res.data));
    } catch (err) {
      dispatch(Creators.failedData1(err.message));
    }
  };
}