How do I do reload on 401 and 403 responses from API? #4779
-
The webapp I'm currently transforming from saga/axios to RTK Query uses apache shiro. The jersey resources are annotated with shiro-jaxrs annotations. That means that when an HTTP call is made I get a 401 response when not logged in, and 403 when logged in but without privileges to make the operation. What I do in axios/saga is to make a saga listen to error actions and for all actions caused by 401 or 403 on the API, do a reload of the webapp and let shiro decide what to do (i.e. do a login, or route to the "not authorized" page). Is there a simple way to do the same thing in RTK query? Do I need to look into RTK listeners? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I created a reducer that handles rejected actions from HTTP API calls and does a reload of the current URL on 401 or 403 https://gist.github.com/steinarb/328a8ebe87ed7bf0e755695915c108b6 This works: a 401 on the API will send me to the login page and shiro will send me to the originating URL after a successful login (and react router will send me to the originating component). |
Beta Was this translation helpful? Give feedback.
-
Reducers should be pure and have no side effects - the right place for this would be in a middleware or a listener import { isAnyOf } from "@reduxjs/toolkit"
const isRejectedRequest = isAnyOf(
api.endpoints.getButikker.matchRejected,
api.endpoints.getHandlinger.matchRejected,
api.endpoints.getOversikt.matchRejected,
api.endpoints.postEndrebutikk.matchRejected,
api.endpoints.postNybutikk.matchRejected,
api.endpoints.postNyhandling.matchRejected,
)
startListening({
matcher: isRejectedRequest,
effect: ({ payload }) => {
const { originalStatus } = payload;
const statusCode = parseInt(originalStatus);
if (statusCode === 401 || statusCode === 403) {
location.reload(true);
}
}
}) |
Beta Was this translation helpful? Give feedback.
Reducers should be pure and have no side effects - the right place for this would be in a middleware or a listener