Skip to content

Instantly share code, notes, and snippets.

@sbycrosz
Last active May 4, 2020 14:24
Show Gist options
  • Save sbycrosz/455b2b1f128a04119088ec89b0734782 to your computer and use it in GitHub Desktop.
Save sbycrosz/455b2b1f128a04119088ec89b0734782 to your computer and use it in GitHub Desktop.
SimpleReducer_LoadingReducer.js
// api/loadingReducer.js
const loadingReducer = (state = {}, action) => {
const { type } = action;
const matches = /(.*)_(REQUEST|SUCCESS|FAILURE)/.exec(type);
// not a *_REQUEST / *_SUCCESS / *_FAILURE actions, so we ignore them
if (!matches) return state;
const [, requestName, requestState] = matches;
return {
...state,
// Store whether a request is happening at the moment or not
// e.g. will be true when receiving GET_TODOS_REQUEST
// and false when receiving GET_TODOS_SUCCESS / GET_TODOS_FAILURE
[requestName]: requestState === 'REQUEST',
};
};
@NaiveGeeek
Copy link

can you please explain how this approach can be used in react project? I have gone through the article but didn't get it It will be better if you can share working example of the code. Thanks

@tscolbert
Copy link

I was a little confused at first too when reading the article, but after thinking about it and then trying it out, it makes a lot of sense. If you've done everything that's in the article and have at least one other reducer it should all plug right in. The one thing missing in the article was the part where you combine the loading reducer with your other reducers. I'm assuming that was thought of as a given and that's why it wasn't included explicitly.

For example:

const rootReducer = combineReducers({
  myOtherReducer,
  loadingReducer
});

Personally, and this may be just me, but I prefer to change this code from this sample to something like:

return {
  ...state,
  isLoading: requestState === 'REQUEST',
};

Of course, isLoading can use whatever verbiage you like, and I'm not sure if there's any standard on that, but if so you may prefer to do that.

Otherwise, you can pretty much throw exactly what's in the article into your react/redux code.

If there's some other part that you're having an issue with, I can try to help more.

@NaiveGeeek

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment