Dispatching an action from middleware results in a strange behavior - redux

Redux newbie here. I understand the core concept of actions, middleware, and reducers, but one of the code snippets works not as I expected. I don't think that it's a bug, but I want to know why things happened in that way.
So, here is a code:
const middlewareOne = store => next => action => {
console.log('Middleware one recived action', action.type)
switch (action.type) {
case 'A':
return next({ type: 'B' })
default:
return next(action)
}
}
const middlewareTwo = store => next => action => {
console.log('Middleware two recived action', action.type)
switch (action.type) {
case 'B':
store.dispatch({ type: 'D' })
return next({ type: 'C' })
default:
return next(action)
}
}
function reducer(state, action)
console.log('Reducer received action', action.type)
return state
}
I have actions A, B, C, and D, two middlewares, and reducer.
First middleware receives action A and produces action B by calling next() function.
Second middleware receives action B and produces action C, and, dispatches an action D.
As I understand, there is nothing wrong with dispatching actions from middleware, but the result was very surprising for me.
Here is a console output for this code
Middleware one receive action A
Middleware two receive action B
Middleware one receive action D
Middleware two receive action D
Reducer received action D
Reducer received action C
So, what I except:
As I know, next() function passes the action to the next middleware or to the reducer if there are no middlewares in the chain, but dispatch puts action to the beginning of the pipeline (all middlewares and finally, the reducer). So, with that idea in mind, I think that action C will be reduced at first (since it's already in the middlewares pipeline), and only after that middlewares start to processing action D, but the result is completely opposite. Can you please explain to me why this happens.
Best regards, Vitaly Sulimov.

I'm relatively new to redux as well, the way I understand it, these calls aren't async so they are performed in order. You dispatch D first, so that will go through the whole chain of middlewares and reducers before the call to Next happens.
so your return next({ type: 'C' }) call only happens after store.dispatch({ type: 'D' }) finished processing

Related

#ngrx Action called Infinitely with Effects

Please forgive me if this is an easy answer. I have a complicated login logic that requires a few calls before a user has a complete profile. If a step fails, it shouldn't break the app -- the user just doesn't get some supplemental information.
The flow I'm looking to achieve is this:
Call Revalidate.
Revalidate calls RevalidateSuccess as well as ProfileGet (supplemental fetch to enhance the user's state).
ProfileGetSuccess.
To save tons of code, the actions exist (it's a giant file).
The app kicks off the action: this._store.dispatch(new Revalidate())
From there, we have the following effects:
#Effect()
public Revalidate: Observable<any> = this._actions.pipe(
ofType(AuthActionTypes.REVALIDATE),
map((action: Revalidate) => action),
// This promise sets 'this._profile.currentProfile' (an Observable)
flatMap(() => Observable.fromPromise(this._auth.revalidate())),
// Settings are retrieved as a promise
flatMap(() => Observable.fromPromise(this._settings.get())),
switchMap(settings =>
// Using map to get the current instance of `this._profile.currentProfile`
this._profile.currentProfile.map(profile => {
const onboarded = _.attempt(() => settings[SettingsKeys.Tutorials.Onboarded], false);
return new RevalidateSuccess({ profile: profile, onboarded: onboarded });
}))
);
//Since I couldn't get it working using concatMap, trying NOT to call two actions at once
#Effect()
public RevalidateSuccess: Observable<any> = this._actions.pipe(
ofType(AuthActionTypes.REVALIDATE_SUCCESS),
mapTo(new ProfileGet)
);
#Effect()
public ProfileGet: Observable<any> = this._actions.pipe(
ofType(AuthActionTypes.PROFILE_GET),
// We need to retrieve an auth key from storage
flatMap(() => Observable.fromPromise(this._auth.getAuthorizationToken(Environment.ApiKey))),
// Now call the service that gets the addt. user data.
flatMap(key => this._profile.getCurrentProfile(`${Environment.Endpoints.Users}`, key)),
// Send it to the success action.
map(profile => {
console.log(profile);
return new ProfileGetSuccess({});
})
);
Reducer:
export function reducer(state = initialState, action: Actions): State
{
switch (action.type) {
case AuthActionTypes.REVALIDATE_SUCCESS:
console.log('REVALIDATE_SUCCESS');
return {
...state,
isAuthenticated: true,
profile: action.payload.profile,
onboarded: action.payload.onboarded
};
case AuthActionTypes.PROFILE_GET_SUCCESS:
console.log('PROFILE_GET_SUCCESS');
return { ...state, profile: action.payload.profile };
case AuthActionTypes.INVALIDATE_SUCCESS:
return { ...state, isAuthenticated: false, profile: undefined };
default:
return state;
}
}
As the title mentions, dispatching the action runs infinitely. Can anyone point me in the right direction?
The answer lies here:
this._profile.currentProfile.map needed to be this._profile.currentProfile.take(1).map. The issue wasn't the fact that all my actions were being called, but because I was running an action on an observable, I suppose it was re-running the action every time someone was touching the observable, which happened to be infinite times.
Moreso, I was able to refactor my action store so that I can get rid of my other actions to call to get the rest of the user's data, instead subscribing to this._profile.currentProfile and calling a non-effect based action, ProfileSet, when the observable's value changed. This let me remove 6 actions (since they were async calls and needed success/fail companion actions) so it was a pretty big win.

Should I dispatch multiple actions in a single action creator, or change multiple properties in a single action type?

Say you are fetching data from a database - is it better to use an action creator like:
dispatch(fetchDataStart());
//then on success
dispatch(fetchDataSuccess(data));
And then have the reducer part look like:
case FETCH_DATA_START:
return { ...state, isFetching:true };
case FETCH_DATA_SUCCESS:
return { ...state, isFetching:false, data:action.data };
Or is it better to separate the fetching-logic from the data-logic and do something like this:
dispatch(fetchDataStart());
//then on success
dispatch(fetchDataFinish());
dispatch(updateData(data));
reducer:
case FETCH_DATA_START:
return { ...state, isFetching:true };
case FETCH_DATA_FINISH:
return { ...state, isFetching:false };
case UPDATE_DATA:
return { ...state, data:action.data };
The initial. The latter doesn't make much sense unless it's executed async.
Normally you would use an action to describe your intent fetchData is a reasonable name. A reducer will set the state to loading. Than the middleware will run with the the action and afterwards the middleware will trigger an action to inform the fetch is done, something like fetchSuccess and fetchError. You're allowed to do whatever is in the middle. If you want to trigger a FETCH_DATA_LOADING action after your fetchData action, because you have need for a very cool reducer to listen for it, please do so.The same argument for when the middleware returns. Please keep your actions as generic as possible so the middleware logic can be reused.

Redux middleware not dispatching new actions

I'm creating a Redux middleware that listens for a specific action. If that action type matches what I'm looking for, I want to dispatch another action. The reason for this is because I have different components with some shared functionality, so I want to update actions to have similar types, but different payloads (term), like so:
const updateActions = store => next => action => {
console.log(action);
if (action.type === 'UNIQUE_ACTION_A') {
return next({ type: 'NEW_ACTION', term: 'new_action_a_test' });
} else if (action.type === 'UNIQUE_ACTION_B') {
return next({
type: 'NEW_ACTION',
term: 'new_action_b_test'
});
}
return next(action);
};
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk, updateActions))
);
The problem I'm having is that these actions are not dispatching. When I console.log all actions, they continue to run as normal, rather than dispatching the new actions. It's as if the call to dispatch these actions are just being ignored. What am I doing incorrectly here? Thanks!
There's a difference between next and dispatch inside middleware. dispatch sends an action to the very start of the dispatch chain, which will cause it to run through all the middleware in the pipeline. next sends it to the next middleware after this one, and eventually to the reducers. By calling next({type : "NEW_ACTION"}), you're sending it to the next middleware, and this middleware will never see "NEW_ACTION".
Also see the Redux FAQ entry on next vs dispatch in middleware.

Redux will execute all subscription callbacks every time an action is dispatched?

Gee, I feel foolish about this, but I have read every part of: http://redux.js.org/ (done the egghead tutorials, and read 4 times the FAQ at: http://redux.js.org/docs/faq/ImmutableData.html
What I did was stub one of my reducers, to always return state, and that is the only reducer being called (checked with breakpoints). Even so, my subscribe event is being called every time the reducer returns state. What Do I not understand? (Action.SetServerStats is being called at a 1Hz rate, and the subscribe is also being called at a 1Hz Rate
BTW the Chrome Redux Extension says thats states are equal, and the React Extension for Chrome with Trace React Updates, is not showing any updates.
I will be glad to remove the question, when someone clues me in. But right now, what I see each each of the reducers being called at 1Hz, and all of them returning the slice of the store that they got (state).
So do I not understand subscribe, and that it returns every time even when the store tree does not get modified (and it is up to react-redux to do shallow compare to figure out what changed if any?)
create store & subscribe
let store = createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunk)))
store.subscribe(() => console.log("current store: ", JSON.stringify(store.getState(), null, 4)))
reducers.js
import A from './actionTypes'
import { combineReducers } from 'redux'
export const GLVersion = (state = '', action) => {
switch (action.type) {
case A.SetGLVersion:
return action.payload
default:
return state
}
}
export const ServerConfig = (state = {}, action) => {
switch (action.type) {
case A.SetServerConfig: {
let { ServerPort, UserID, PortNumber, WWWUrl, SourcePath, FMEPath } = action.payload
let p = { ServerPort, UserID, PortNumber, WWWUrl, SourcePath, FMEPath }
return p
}
default:
return state
}
}
export const ServerStats = (state = {}, action) => {
switch (action.type) {
case A.SetServerStats:
return state
// let { WatsonInstalled, WatsonRunning, FMERunning, JobsDirSize } = action.payload
// let s = { WatsonInstalled, WatsonRunning, FMERunning, JobsDirSize }
// return s
default:
return state
}
}
export default combineReducers({ GLVersion, ServerConfig, ServerStats })
Correct. Redux will execute all subscription callbacks every time an action is dispatched, even if the state is not updated in any way. It is up to the subscription callbacks to then do something meaningful, such as calling getState() and checking to see if some specific part of the state has changed.
React-Redux is an example of that. Each instance of a connected component class is a separate subscriber to the store. Every time an action is dispatched, all of the wrapper components generated by connect will first check to see if the root state value has changed, and if so, run the mapStateToProps functions they were given to see if the output of mapState has changed at all. If that mapState output changes, then the wrapper component will re-render your "real" component.
You might want to read my blog post Practical Redux, Part 6: Connected Lists, Forms, and Performance, which discusses several important aspects related to Redux performance. My new post Idiomatic Redux: The Tao of Redux, Part 1 - Implementation and Intent also goes into detail on how several parts of Redux actually work.

Allow reducer to have access to state

I have a reducer that maintains the currently visible item from a list of some sort, with a case for displaying the next and previous item:
export function currentIndex(state = null, action) {
switch (action.type) {
case types.INCREMENT:
return state + 1
case types.DECREMENT:
return state - 1;
}
}
I also have a random state which is initially false but when set to true I want the currentListItem reducer to be able to account for this and output a a random number instead.
Which is the most idiomatic way of doing this in redux?
The idiomatic solution is to transfer your reducer logic into a thunk using a middleware package such redux-thunk (or similar).
This allows you to treat special kinds of actions as functions which means you can extend a plain action with specific action-related logic. The example you give of needing to access the state to conditionally determine the action logic is an excellent use-case for redux-thunk.
Below is a example of how you might pull the logic out of your reducer into a thunk. You should note that, unlike reducers, thunks explicitly support fetching state and dispatching subsequent actions via the getState and dispatch functions.
Thunk Example
export const increment= () => {
return (dispatch, getState) => {
const state = getState()
const delta = (state.random) ? getRandomNumber() : 1
dispatch({
type: INCREMENT,
delta
})
}
}
export function currentIndex(state = null, action) {
switch (action.type) {
case types.INCREMENT:
return state + action.delta
}
}

Resources