redux-logic
redux-logic copied to clipboard
QUESTION: Multiple Logics For Single Action
Here's my demo code:
const FETCH_USER = 'FETCH_USER#auth#block-ui';
const actionAuthValidationLogic = createLogic({
type: /#\bauth\b/,
validate({ getState, action }, allow, reject) {
const { isLoggedIn } = selector(getState());
if (isLoggedIn) {
allow(action);
} else {
reject(push('/login'));
}
}
});
const userRetrievalLogic = createLogic({
type: FETCH_USER,
async process({ getState }, dispatch, done) {
const response = await api.get('/v1/user/current', getState);
dispatch(setUser(JSON.parse(response.getBody()));
done();
}
});
The idea is fetchUser action requires authentication and by doing so like above, allow fetchUser action dispatch or reject and force to redirect to '/login' page depending on authentication status.
There are many other actions that require authentication as well, not only fetchUser action.
I'm sure that if validate and process properties are provided to a single logic, the process hook will not be executed if rejected inside validation hook.
But I'm not sure if it works the same way for a single action, with validate and process hooks are provided to different logics.
I believe I understand what you are asking.
If you validate and process in the same logic then yes the process will only get called if the validation hook had allowed rather than rejected.
If you split things like you have here it would also work fine as long as your auth logic is before your other logic. By calling reject with push('/login') you are stopping the original action from going down any further, and instead you are sending the action to redirect to login.
So all of your other logic as long as it was later in the array that you gave to logicMiddlware, then it will not see the original action. The validate stopped it from being sent to any more of the logic that occur after it.
So yes, what you have would work as long as the auth comes before any other logic it needs to protect against when you registered it with the logicMiddlware. So just put the auth logic earlier in the array and you should be good to go.