Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I trigger errorType in a generalized way? #734

Open
OliDM opened this issue Feb 21, 2022 · 2 comments
Open

How can I trigger errorType in a generalized way? #734

OliDM opened this issue Feb 21, 2022 · 2 comments

Comments

@OliDM
Copy link
Contributor

OliDM commented Feb 21, 2022

I'm trying to manage the loading state of request fired inside thunks based on the thunks startType, successType and failType actions. I have listeners in place on each thunk based on a naming convention. My issue right now is that thunks do not fire the failType action when a promise is rejected. I could not find a store configuration parameter to enable this or a general way to handle this without touching each thunk since from what I've seen the fail function comes from the helpers param.

This is my current approach to handle the loading and errors

import { actionOn } from "easy-peasy";

const SUFFIX = "Request";

function createLoadingThunks(store) {
  const reducerNames = Object.keys(store);

  let newStore = {};
  reducerNames.map((reducerName) => (newStore[reducerName] = enhance(store[reducerName])));

  return newStore;
}

const enhance = (reducer) => {
  const thunkNames = Object.keys(reducer).filter((key) => key.endsWith(SUFFIX));

  return {
    ...reducer,
    loading: false,
    ...makeListener(thunkNames),
  };
};

function makeListener(thunkNames) {
  return {
    loadingStart: actionOn(getTypes(thunkNames, "startType"), (state) => {
      state.loading = true;
    }),
    loadingEnd: actionOn(getTypes(thunkNames, "successType"), (state) => {
      state.loading = false;
    }),
    loadingFail: actionOn(getTypes(thunkNames, "failType"), (state, error) => {
      state.loading = false;
      state.error = error.message;
    }),
  };
}

function getTypes(thunkNames, actionType) {
  return (actions) => thunkNames.map((name) => actions[name][actionType]);
}

export default createLoadingThunks;

@jmyrland
Copy link
Collaborator

Did you find a solution to this?

@OliDM
Copy link
Contributor Author

OliDM commented Sep 15, 2022

@jmyrland Nope.

As a workaround, I found the way it used to be done before and re-introduced it using patch-package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

2 participants