Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Created November 21, 2019 09:04
Show Gist options
  • Save zzdjk6/bdfc6d53cbc1f3cfae9ebe5f91c466a6 to your computer and use it in GitHub Desktop.
Save zzdjk6/bdfc6d53cbc1f3cfae9ebe5f91c466a6 to your computer and use it in GitHub Desktop.
// To know more about ducks, see https://github.com/erikras/ducks-modular-redux
import { Action } from 'redux-actions';
import { RootState } from '../../store';
import { createSelector } from 'reselect';
// State
// To know more about Record type, see https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
export type ErrorState = Record<string, Error | null>;
// Reducer
export default (state: ErrorState = {}, action: Action<any>): ErrorState => {
const { type } = action;
const matches = /(.*)\/(REQUEST|SUCCESS|FAILURE)/.exec(type);
// Ignore non-routine actions:
// A routine action should have one of three suffixes:
// ['/REQUEST', '/SUCCESS', '/FAILURE']
if (!matches) return state;
const [, routineType, status] = matches;
return {
...state,
// Set error state to the payload only when the status is "FAILURE"
// Otherwise set the error state to null
[routineType]: status === 'FAILURE' ? action.payload : null
};
};
// Selectors
// Select the whole error state
export const selectErrorState = (state: RootState) => state.domainData.error;
// Select error for a given routine
export const selectError = (routineType: string) => {
return createSelector([selectErrorState], (state: ErrorState) => {
return state[routineType];
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment