I have many async Redux actions that all fetch different resources from an API. Now if the user is not authenticated all these API calls will return a 401.
Now I am looking for a way to catch all these and automatically navigate the user to the login page using history.push('/login'). Now I thought of a "smart" way of doing this by having all these async actions set a 401 status to the action object. Subsequently a reducer would catch all these actions by their status property being equal to 401. The user would then be navigated to the login page by a history.push() call inside this reducer:
import { history } from '../routers/AppRouter'
export default (state = {}, { status }) => {
if (!status) return state
switch (status) {
case 401: {
history.push('/login')
break
}
default: {
}
}
return state
}
However, as I already expected, but hoped to false, this is not possible, since a reducer is not allowed to have side-effects... I get the following error as a result:
Error: You may not unsubscribe from a store listener while the reducer is executing.
My question thus is, if there is a way to make this work inside the reducer? Or is there some other way of doing this. I'd really like to avoid having to put the following code in every async action:
if (response.status === 401) history.push('/login')