Search code examples
javascriptreduxreact-reduxmiddlewareredux-toolkit

Axios call in redux-toolkit middleware gone into infinite loop


I have redux-toolkit for state management in my react project and I am using one Middleware function for doing change in the payload before sending to the reducer. In the middleware file, I am doing one Api call for changing text into ES but because of error into my Api this middleware function goes into the infinite loop. You can see the middleware function and Api call code in below snippet.

import { getSpanishText } from "../../helpers/storeSpanishText";

export const kioskSettingsMiddleware = (store) => (next) => async (action) => {
    const actionType = action.type;
    if (actionType === "kisokSettings/saveKioskPortalSettings") {
      const prevState = store.getState().kioskSettings;
      const data = action.payload;
      let settingObject = {
        autoDisconnect: data.auto_hang_up_call,
        multiPMS: data?.is_multi_pms_mapping,
      };

    if (
      data?.is_complete_operation_message &&
      data?.complete_operation_message !== prevState?.completeMessage
    ) {
      settingObject["completeMessage"] = data?.complete_operation_message;
      settingObject["EScompleteMessage"] = await getSpanishText(
        "EScompleteMessage",
        data?.complete_operation_message
      );
    }
   
    return store.dispatch({ type: actionType, payload: settingObject });
  }
  return next(action);
}

Here is the API call code

export const getSpanishText = (key, msg) => {
  return axios
    .get(`https://translation.googleapis.com/language/translate/v2`, {
      params: {
        key: TRANSLATE_API_KEY,
        q: msg,
        target: "es",
      },
    })
    .then((res) => {
      if (res.status === 200) {
        ipcRenderer.send("logs", {
          type: "info",
          msg: `ES TRANSLATION- [${key} : ${res.data.data.translations[0].translatedText}]`,
        });
        return res.data.data.translations[0].translatedText;
      }
    })
    .catch((err) => {
      ipcRenderer.send("logs", {
        type: "info",
        msg: `FALLBACK EN - [${key} : ${msg}]`,
      });
      return msg;
    });
};

Solution

  • Your

        return store.dispatch({ type: actionType, payload: settingObject });
    

    starts a new dispatch with the same action type - so it will run into the same middleware again.

    Maybe you wanted to call

    return next({ type: actionType, payload: settingObject })
    

    instead?