Custom Action Types
You can add support for additional action types to a resourceReducer
using plugins.
The name 'plugins' may seem intimidating, but don't be worried. Plugins are reducers that you can reuse for any resource slice. If you know how to write a reducer, then you know how to write a plugin.
Using a Plugin
You define plugins for each resource type when you call resourceReducer
. The second argument to that function is an options
option, and within it you can pass plugins
as an array:
Writing a Plugin
A plugin is a function that with the following signature:
Where resourceType
and options
are the arguments that you passed to resourceReducer
.
The return value, reducerFunction
, is also a function. This returned function has the same signature as a Redux reducer:
where state
is the value of the state after running it through the built-in reducer and action
is the action that was dispatched.
The simplest plugin then (which doesn't do anything), would look like this:
If you prefer using arrow functions, you might choose to write this like so:
This plugin isn't very exciting, so let's look at more realistic examples.
Selecting Resources
Let's build a plugin that lets a user select resources. The code for this plugin looks like this:
You would then use this plugin like so:
Customizable Plugins
You can write plugins that can be customized per-slice by taking advantage of the fact that the resourceReducer
's options are passed into plugins. For instance, if you had a plugin like the following:
then you could trigger the special behavior by passing useSpecialBehavior: true
as an option to resourceReducer
:
If this API isn't to your liking, then you can also just wrap the plugin itself in a function, like so:
which would be used in the following way:
You may dislike this approach due to the tripley-nested functions. That's fine, because either way works. Use the version that makes the most sense to you.
Best Practices
Because plugins are so similar to reducers, you can use a switch
statement and support multiple action types within each plugin. This is usually a good thing, but be mindful of keeping each plugin limited to a single responsibility.
For example, in the above example of a plugin for selecting resources, it supports two Action types – one for selection, and one for deselection. This plugin encapsulates that one responsibility, and it isn't responsible for any other Action types.
We recommend having a plugin for each distinct responsibility.
Last updated