Let's say my Redux global state looks as follows:
{
micEnabled : Boolean,
filterEnabled : Boolean
}
A React component has a "Enable Mic" button that, upon clicked, should perform an async operation (that may take a while) and resolves with a Promise. In order to run such an async operation I can add a custom Redux middleware into the store, or can use redux-thunk, etc. That's not the question.
Here my question: Which one should be the name of the Redux action invoked on "Enable Mic" click?
When there is no async stuff involved it's common to name Redux actions as "setters" (SET_CURRENT_TIME) or expressive actions (TOGGLE_FILTER) that will be directly used by reducers to update state. So one may suggest ENABLE_MIC for my use case above, but the fact is that such an action (let's say "action 1") should not directly update state.micEnabled.
Instead, my Redux middleware will intercept action 1 (ENABLE_MIC), run the async operation and, once resolved, dispatch yet another Redux action ("action 2") so the corresponding reducer would update state.micEnabled. So "action 2" could be MIC_ENABLED.
To summarize:
Click on button dispatches ENABLE_MIC.
Redux middleware intercepts it and performs async operation.
On resolved, middleware dispatches MIC_ENABLED.
Reducer updates state.micEnabled.
Ok, this makes lot of sense. The problem is that, within my actions, I also have tons of "common actions" that are dispatched to reducers to update state (such as TOGGLE_FILTER):
Click on checkbox dispatches TOGGLE_FILTER.
Reducer updates state.filterEnabled.
So both ENABLE_MIC and TOGGLE_FILTER represent "commands" or "requests", but just one of them (TOGGLE_FILTER) is used by reducers to update state. In the other side, the reducer also listens for MIC_ENABLED action (which is not a "command" or "request" but something that has happened or an event).
So, is there any recommendation for naming these kinds of Redux actions in a comprehensible so, by looking at the name of all my Redux actions, I can easily know which ones update state and which ones just dispatch another actions?
Treat it like an AJAX request and call them ENABLE_MIC_REQUEST which can result in ENABLE_MIC_SUCCESS or ENABLE_MIC_FAILURE (if this is possible in your scenario). You could cover everything in one action creator, using thunk, named something like enableMic. That should be fairly transparent.
Only ENABLE_MIC_SUCCESS would then flip micEnabled in the reducer. I'd recommend to rename that to isMicEnabled btw to make it super clear that it's a boolean flag.
When handling ENABLE_MIC_FAILURE you can show error messages, or do whatever is appropriate in your app.
Related
I am slowly migrating my app from plain redux to redux-toolkit.
One patter I noticed I have is as follows:
An async thunk that fetches stuff and dispatches start/complete/error actions
A middleware that reacts to the complete action
Other functions that also dispatch the complete action
Previously I converted other thunks to be a simple createAsyncThunk action thunk and react to the generated thunk states fulfilled|pending|rejected, however on this situation I need to be able to dispatch the fulfilled one from several places.
I don't think is idiomatic (nor a good idea) if I dispatch the fulfilled type manually by doing dispatch({ type: myThunk.fulfilled, payload}).
My guess is that I should create another normal sync action creator and dispatch that from the thunk, from the other several places and use that one to react to it on the store and the middleware and totally ignore the thunk.fulfilled state.
Is my assumption correct?
I have two reducers combined using combineReducers()
UI Reducer has a 'isLoginOpen' key (true/false) - When true a login modal appears.
Auth Reducer has 'isAuthenticated' key - (true/false) Which states if the user is logged in
I also have an action creator called OpenLoginModal() which causes the UI reducer to make 'isLoginOpen' to become true.
I only want to allow this behavior when 'isAuthenticated' is false. I.E, I only allow to show the login modal when the user isn't logged in.
The problem is: 'isAuthenticated' is in a different reducer, and I don't want to duplicate it to UI reducer.
How should I resolve this issue?
Reducers should be concerned about updating the state.
You should use selectors to calculate the state of the application including which actions are allowed.
In your case the code calling the action creator (or the action creator itself if using thunk) can select both values from the store and decide what to do.
Per the Redux FAQ entry on sharing state between reducers:
Many users later want to try to share data between two reducers, but find that combineReducers does not allow them to do so. There are several approaches that can be used:
If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
You may need to write some custom functions for handling some of these actions. This may require replacing combineReducers with your own top-level reducer function. You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
Async action creators such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
Given your use case, I'd suggest writing a thunk action creator that checks state.auth.isAuthenticated, and only dispatches the action if that's false.
I would like many different redux actions in my app to all trigger common functionality in a specific reducer. I would like to avoid having to either repeat some flag in every action creator (like doThing: true) that the reducer looks for. I also don't want to have to have the reducer just look for every individual action that falls into this category, since that also requires someone to remember to do this every time they add a new action, like adding the flag.
I was thinking of dispatching a second action every time one of these actions is going to be dispatched. This would not be hard to do, but I'd rather not have 2 actions dispatched every time one thing happens. It seems like it would pollute the state history.
Is there a common way of solving this problem?
For more context to my specific problem, the specific feature is related to the API client my app uses to talk to our API. On every successful response, we'd like to do something in a reducer to update the state, and on every failed response, we'd like to do something else.
There are many different success and failure actions (such as ITEM_FETCH_SUCCESS or WIDGET_UPDATE_FAILURE), and adding a flag to all of them would be hard to remember to do when new ones are added.
Since all api requests go through a single function, that function COULD dispatch generic REQUEST_SUCCESS and REQUEST_FAILURE actions. But this would mean every response from the server would dispatch 2 actions (REQUEST_SUCCESS and ITEM_FETCH_SUCCESS). This is obviously not ideal since it would mean many more actions in my state history.
Assuming the generic REQUEST_SUCCESS and REQUEST_FAILURE actions are updating their own specific portions of the state-tree then it is fine to dispatch them as distinct actions. Doing this does not necessarily imply the pollution of your state history but can simply be a better description of the app's intentions.
ITEM_FETCH_SUCCESS: Change state for item
REQUEST_SUCCESS: Change state for request
WIDGET_UPDATE_FAILURE: Change state for widget
REQUEST_FAILURE: Change state for request
You can see that whilst the actions are intimately related, they are not necessarily the same thing as they change different parts of the state tree.
Accepting this, the question is: How best to implement the action-pairs so that adding new actions does not mean remembering to add its corresponding REQUEST_* partner?
I would consider applying a simple redux middleware component. This could intercept the return from your api and dispatch the appropriate REQUEST_* action automatically.
Here is an example from some live code. This middleware intercepts a disconnect event raised by a websocket and automatically dispatches a custom action as a result. It at least shows the principle:
//Dispatch a disconnect action when the websocket disconnects
//This is the custom action provided by the middleware
import io from 'socket.io-client'
import { actions } from './action'
const websocket = ({ websocketUrl }) => store => {
const socket = io(websocketUrl)
socket.on('disconnect', () => store.dispatch(actions.disconnect()))
}
export default websocket
//Apply the custom middleware via the redux createStore function
//Also include the thunk middleware because it is useful
import { applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import websocket from './middleware'
function websocketize (opts) {
return createStore => (reducers, initial, enhancer) => {
const middleware = applyMiddleware(thunk, websocket(opts))
return createStore(reducers, initial, middleware)
}
}
export default websocketize
// Create the top-level redux store passing in the custom middleware enhancer
const opts = {websocketUrl: env.WEBSOCKET_URL}
const store = createStore(reducers, websocketize(opts))
This implementation keeps everything inside your reducers as opposed to having logic outside in an interception(middleware). Both ways are valid.
Try a sub-reducer pattern. I usually feel gross when I see it used(because it is usually used wrong), but your situation sounds perfect.
Extract duplicate functionality out of your reducers to one single
sub-reducer.
Then pass that reducer as a function to all others that need it.
Then pass the action and state onto the sub-reducer.
The sub-reducer does it's thing and returns that slice of state to
your parent reducer to allow you to do whatever you want with it
there (ie return it, mutate some more, some logic).
Also if you are tired of worrying about typing out "all the stuff" for async then I highly recommend you try out redux-crud.js
It also is possible and a simple way to do that would be to give every action to one reducer and let it do that common mutation, in a single case:
case actionOne
actionTwo
actionThree
actionFour: {
//do common stuff here
}
. But you said it is not duplicated, it is similar, which means your case becomes complicated by branching logic. I also don't recommend this. Keep cases simple so you can easily catch invalid mutations. This should be a super power of redux that it is easy to catch mutation errors. And for this reason and many others I don't recommend normalizing data in the front end.
I can't see a clear way to know when a particular action has fired or particular state has updated from the context of a redux-thunk action creator.
I want to do something like this:
Dispatch an action
Detect a possible recoverable error condition
Error condition dispatches a different action signalling recovery process initiating
Wait for recovery to complete
Proceed with current action or re-dispatch it
Concrete example:
User interaction triggers API call action
Note that API call failed, needs login
Dispatch 'LOGIN_REQUIRED' action, which pops up a <dialog> for user.
Wait for logged in state to change (or LOGIN_SUCCESS action to occur, whatever).
Make same API call again
If you want to check for a specific action to be dispatched, you'll need middleware.
If you want to, in effect, "subscribe a given bit of state", Redux doesn't provide a built-in way to do that. There are, however, a number of utilities that implement that kind of logic for you. See the Redux FAQ at http://redux.js.org/docs/FAQ.html#store-setup-subscriptions , and also the list of store subscription addons in my Redux addons catalog. (The list of Redux middlewares may also have something useful for the "listen for an action" scenario.)
for visualizing what happens in store you can use:
import {composeWithDevTools} from 'redux-devtools-extension';
and create your store as: (for instance with thunk middleware)
const store = `createStore(rootReducer,composeWithDevTools(applyMiddleware(thunk)));`
then you can use the extention in browser.
you can have access to your state by {connect} from 'react-redux' as props.
your actions then will change the state via reducers, this will cause your component receive new props so you can have your logic in
componentWillReceiveProps(nextProps) {/*your business logic*/}
I am refactoring my app to use redux, and it's great.
One thing I'd like to do is to dispatch an initial action at the beginning, and every reducer would manage to initialize themselves at that moment.
Let's say i have a main.js that create the stores, the routes, etc. In that file, I could do:
store.dispatch({ type: 'app/init' });
If I do this, the action type app/init can be intercepted in each reducer which needs to initialize itself.
An example use case (among others)
When the app is launched, a third party library must be called to see if a user is currently authenticated. If so, a LOGIN_SUCCESS action must be triggered with that user data.
I'd like to see this code in the same file as the authentication reducer, triggered by a global init action (which would mean the store is created).
The problem
In the reducer (where init action is managed), other actions cannot be dispatched.
The advised way of implementing actions is by defining action creators, which is indeed very clean, and let us use middleware like thunks to dispatch other actions.
I could use init() action creators for each reducer (I define related actions and reducer in the same "ducks" file), but that means importing/calling each of them in main.js, which is what I was trying to avoid by dispatching the action directly.
How to get the best of all worlds by having one single app/init action dispatched, and being able to intercept it in each store and dispatch other actions?
Note: I thougth of just implementing those initialization code in each reducer, inline, but I do not have standard access to the dispatcher that way?
The reducer just calculates the next state based on an action. In Redux, it’s not the right place to put side effects like calling an API.
If you want to orchestrate an asynchronous workflow of actions, I suggest you to look at Redux Saga. It lets you define long-running functions (“sagas”) that can “wait” for specific actions, execute some side effects, and dispatch more actions.