neuron
Home / core / Middleware
Middleware is used to implement logic during the lifecycle of state changes. It has access to the dispatched state and payload.
There are three different middleware types that can be called at different times during the dispatch lifecycle.
Invokes only once when the Neuron is first instantiated.
const pokemon = new Neuron("Pikachu", {
onInit: () => {
//do something when Neuron first instantiates
},
});
Invokes every time a set or dispatch method is fired. It runs before state is updated.
const pokemon = new Neuron("Pikachu", {
onDispatch: () => {
//do something every time state is updated
},
});
Invokes after the store is updated. This will run even if the update fails.
const pokemon = new Neuron("Pikachu", {
onCallback: () => {
//do something every time state is updated
},
});
The payload is an object of properties and methods that is made available to each middleware mutator function. This allows logic to manipulate state or even cancel a dispatch in mid flight.
Properties
key - Neuron key.
prevState - Previous state.
state - Dispatched state. Mutable
features - Features set for the store item. Module specific props passed to the features property in the Neuron options.
Methods
cancelDispatch - Cancels the dispatch.
isDispatchCancelled - Checks to see if the dispatch was cancelled.
Make sure dispatched state is always capitalized.
const pokemon = new Neuron("Pikachu", {
onDispatch: (payload) => {
const capitalizedState = `${payload.state
.charAt(0)
.toUpperCase()}${phrase.slice(1)}`;
payload.state = capitalizedState;
},
});
Cancel a dispatch if the state does not meet a certain condition.
const pokemon = new Neuron("Pikachu", {
onDispatch: (payload) => {
if (payload.state === "trubbish") {
payload.cancelDispatch();
alert("Trubbish should not exist. Try again");
}
},
});
Update another state if the dispatched state is a certain value.
const trainer = new Neuron("Ash");
const pokemon = new Neuron("Pikachu", {
onCallback: (payload) => {
if (payload.state === "Meowth") {
trainer.set("Team Rocket");
}
},
});
Middleware and payloads when used together can be very powerful and help centralize common state logic in your app.