When you find yourself writing repetitive code, it's time to extract it into a plugin.
Kea has a powerful system for authoring plugins, yet at their core, most plugins simply
logic.extend() and add a few
actions, reducers or listeners to your logic.
If that's all you want to do, it's often not even needed to write a real plugin. A simple function will do.
For example here's a function that just adds an
isLoading state to your logic:
This works, but what if we want to instead do something like this:
For this we will write an actual plugin
myOwnLoadingPlugin and later activate it via the
plugins array on
We just need to move around the code from
addLoading above and place it into the appropriate
This is what such a plugin would look like:
Pretty simple stuff.
The above code probably works well enough, but there's one catch: it's run after
all the other steps (
selectors, etc) are done. Depending on what you're
building, that might not be enough. Luckily there's also a way to also control when this
isLoading reducer is added to your logic.
buildSteps come in.
The core of Kea is just an engine that converts
logic through various
In fact, this is the actual code for the
core plugin just runs each of these steps one by one.
Here are (slightly abbreviated) steps for
There's no magic here. Kea just converts
logic, doing whatever
transformations are necessary.
Thanks to the
buildSteps, your new plugin can run custom code before or after
any of these steps.
If you want to add the
isLoading reducer after all the other reducers, but before
selectors, this is what you should do:
It's as simple as that.
Sometimes it's necessary to directly modify the
logic, like the
buildActions steps did above. However for this
doesn't really matter.
You should, however, never modify the
input in any way in your plugins! The idea is that
every time you build and mount your logic, it should work the same way. Modifying the input
breaks that contract and the build step might produce different results. It's best to avoid that.
If you want to learn more about writing plugins, it's best to just read the code of some of the existing plugins and see how they do things.
See the plugins API page for a list of everything that a plugin can do.