I've built a middleware that shows a toast indicating the state of queries started by rtk-query. Using the functions isPending, isFulfilled and isRejectedWithValue I can update the toast to reflect the current state of the query. That's working fine but now I want to differentiate the kind of request cause there are some specific (a little) of them that is preferable not to show any notification, how can I handle that?
This is the actual middleware that handles my use case:
import {
isFulfilled,
isPending,
isRejectedWithValue,
Middleware,
} from "@reduxjs/toolkit";
import { toast } from "react-toastify";
const queryStatus: Middleware = () => (next) => (action) => {
const TOAST_QUERY_ID = "query-status";
if (isPending(action)) {
toast("Loading", {
isLoading: true,
toastId: TOAST_QUERY_ID,
type: toast.TYPE.DEFAULT,
});
} else if (isFulfilled(action)) {
toast.update(TOAST_QUERY_ID, {
render: "Done",
type: toast.TYPE.SUCCESS,
isLoading: false,
});
} else if (isRejectedWithValue(action)) {
toast.update(TOAST_QUERY_ID, {
render: "Error",
type: toast.TYPE.ERROR,
isLoading: false,
});
}
return next(action);
};
export default queryStatus;
EDIT: One approach (I'm looking for something cleaner):
import {
isFulfilled,
isPending,
isRejectedWithValue,
Middleware,
} from "@reduxjs/toolkit";
import { toast } from "react-toastify";
const queryStatus: Middleware = () => (next) => (action) => {
const TOAST_QUERY_ID = "query-status";
if (isPending(action)) {
toast("Loading", {
isLoading: true,
toastId: TOAST_QUERY_ID,
type: toast.TYPE.DEFAULT,
});
} else if (isFulfilled(action)) {
if (action.meta.arg.type === "mutation") {
toast.update(TOAST_QUERY_ID, {
render: "Done",
type: toast.TYPE.SUCCESS,
isLoading: false,
autoClose: 200,
});
} else {
toast.update(TOAST_QUERY_ID, {
isLoading: false,
autoClose: 100,
});
}
} else if (isRejectedWithValue(action)) {
toast.update(TOAST_QUERY_ID, {
render: "Error",
type: toast.TYPE.ERROR,
isLoading: false,
autoClose: 3000,
});
}
return next(action);
};
export default queryStatus;
Although this approach only handles the mutations differently from queries and not specific endpoints.