In my React application i'm using Long-polling API. In order to automatically send requests on every response i use middleware. But before sending new request, i have to save received data in store. More than that, i want to dispatch another action inside my middleware. So my structure looks like this:
InitLongPoll() -> SendRequest(data) -> ReceiveResponse(data)* -> SendRequest(data)
'*' is my middleware. From there i'm saving data to the store using store.dispatch(responseData) and sending new request using store.dispatch(sendRequest(authData)).
Is it okay to receive that authData using store.getState().authReducer? As far as i know, my middleware should be a pure function and shouldn't depend on external data (store). Thanks in advance.
Is it okay to receive that authData using store.getState().authReducer? As far as i know, my middleware should be a pure function and shouldn't depend on external data (store).
Yes it is. Middleware is the way to introduce side effects into the redux loop, and it can't be a pure function. Your own middleware has a side effect - polling the server.
A redux middleware is the anti-thesis of a pure function, which is defined as:
- The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices (usually—see below).
- Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices (usually—see below).
You can also see in the redux-thunk source code, that it uses getState:
function createThunkMiddleware(extraArgument) {
return ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument);
}
return next(action);
};
}