Fix the loading bar with the new Redux actions (#28422)

This commit is contained in:
Renaud Chaput 2023-12-19 00:19:27 +01:00 committed by GitHub
parent 7cfc078198
commit 8b1eeb2f90
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 54 additions and 30 deletions

View file

@ -1,3 +1,9 @@
import {
isAsyncThunkAction,
isPending as isThunkActionPending,
isFulfilled as isThunkActionFulfilled,
isRejected as isThunkActionRejected,
} from '@reduxjs/toolkit';
import { showLoading, hideLoading } from 'react-redux-loading-bar';
import type { AnyAction, Middleware } from 'redux';
@ -21,25 +27,43 @@ export const loadingBarMiddleware = (
return ({ dispatch }) =>
(next) =>
(action: AnyAction) => {
if (action.type && !action.skipLoading) {
let isPending = false;
let isFulfilled = false;
let isRejected = false;
if (
isAsyncThunkAction(action)
// TODO: once we get the first use-case for it, add a check for skipLoading
) {
if (isThunkActionPending(action)) isPending = true;
else if (isThunkActionFulfilled(action)) isFulfilled = true;
else if (isThunkActionRejected(action)) isRejected = true;
} else if (
action.type &&
!action.skipLoading &&
typeof action.type === 'string'
) {
const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;
const isPending = new RegExp(`${PENDING}$`, 'g');
const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
const isRejected = new RegExp(`${REJECTED}$`, 'g');
const isPendingRegexp = new RegExp(`${PENDING}$`, 'g');
const isFulfilledRegexp = new RegExp(`${FULFILLED}$`, 'g');
const isRejectedRegexp = new RegExp(`${REJECTED}$`, 'g');
if (typeof action.type === 'string') {
if (action.type.match(isPending)) {
dispatch(showLoading());
} else if (
action.type.match(isFulfilled) ??
action.type.match(isRejected)
) {
dispatch(hideLoading());
}
if (action.type.match(isPendingRegexp)) {
isPending = true;
} else if (action.type.match(isFulfilledRegexp)) {
isFulfilled = true;
} else if (action.type.match(isRejectedRegexp)) {
isRejected = true;
}
}
if (isPending) {
dispatch(showLoading());
} else if (isFulfilled || isRejected) {
dispatch(hideLoading());
}
return next(action);
};
};