Convert Redux custom middleware to TypeScript

This commit is contained in:
Alex Gleason 2022-04-24 14:40:14 -05:00
parent 7038d6a844
commit 57e5d81e33
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
3 changed files with 29 additions and 0 deletions

Binary file not shown.

View file

@ -0,0 +1,29 @@
import { showAlertForError } from '../actions/alerts';
import type { AnyAction } from 'redux';
import type { ThunkMiddleware } from 'redux-thunk';
/** Whether the action is considered a failure. */
const isFailType = (type: string): boolean => type.endsWith('_FAIL');
/** Whether the action is a failure to fetch from browser storage. */
const isRememberFailType = (type: string): boolean => type.endsWith('_REMEMBER_FAIL');
/** Whether the error contains an Axios response. */
const hasResponse = (error: any): boolean => Boolean(error && error.response);
/** Whether the error should be shown to the user. */
const shouldShowError = ({ type, skipAlert, error }: AnyAction): boolean => {
return !skipAlert && hasResponse(error) && isFailType(type) && !isRememberFailType(type);
};
/** Middleware to display Redux errors to the user. */
export default function errorsMiddleware(): ThunkMiddleware {
return ({ dispatch }) => next => action => {
if (shouldShowError(action)) {
dispatch(showAlertForError(action.error));
}
return next(action);
};
}