Search code examples
reactjsreduxredux-api-middleware

send custom object to reducer in "redux-api-middleware"


I am using redux-api-middleware.

My Action for fetching account data :

import { RSAA } from "redux-api-middleware";
import { API_ENDPOINT, AUTH_HEADERS } from "../util/constants";
import { ACCESS_TOKEN } from "../util";

export function getAccount(accountID) {
  return {
    [RSAA]: {
      endpoint: `${API_ENDPOINT}/api/Expense/GetAccount/${accountID}`,
      headers: {
        ...AUTH_HEADERS,
        Authorization: `Bearer ${ACCESS_TOKEN}`,
      },
      method: "GET",
      types: ["GET_ACCOUNT_REQUEST", "GET_ACCOUNT_RECEIVE", "GET_ACCOUNT_FAILURE"],
    },
  };
}

My Reducer :

import store from '../util/store';

const INITIAL_STATE = store.setInitialState({
  payload: null,
});

const getAccountReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case "GET_ACCOUNT_REQUEST":
      return {
        ...state,
        isFetching: true,
      };
    case "GET_ACCOUNT_RECEIVE":
      return {
        ...state,
        isFetching: false,
        isSuccess: true,
        payload: action.payload,
      };
    case "GET_ACCOUNT_FAILURE":
      return {
        ...state,
        isFetching: false,
        isSuccess: false,
        payload: action?.payload?.response,
      };
    default:
      return {
        ...state,
      };
  }
};

export default getAccountReducer;

Now, whenever API gives success response, It will go to "GET_ACCOUNT_RECEIVE".
I want to pass "accountID" (which I passed as a parameter in getAccount action) to "GET_ACCOUNT_RECEIVE" reducer. So that I will be able to create payload with key value pairs of different accounts.

{
  [accountID]: {...action.payload},
  [accountID]: {...action.payload},
  [accountID]: {...action.payload},
  [accountID]: {...action.payload},
}

How can I pass "accountID" to the "GET_ACCOUNT_RECEIVE" reducer ?


Solution

  • Looks like https://github.com/agraboso/redux-api-middleware#meta is meant for what you have in mind:

    export function getAccount(accountID) {
      return {
        [RSAA]: {
          endpoint: `${API_ENDPOINT}/api/Expense/GetAccount/${accountID}`,
          headers: {
            ...AUTH_HEADERS,
            Authorization: `Bearer ${ACCESS_TOKEN}`,
          },
          method: "GET",
          types: [
            "GET_ACCOUNT_REQUEST",
            {
              type: "GET_ACCOUNT_RECEIVE",
              meta: { accountID } // <----------------
            },
            "GET_ACCOUNT_FAILURE"
          ],
        },
      };
    }
    

    Not sure if it works exactly like that, but the middleware author(s) seem to have considered this use case. There should be an action.meta besides the payload available in the reducer.