Accessing the original (unmodified) state in a middleware
You might need to access the original, unmodified state within a middleware function in certain scenarios. This is the state before any middleware in the chain has had a chance to modify it. The Aurelia Store plugin provides this capability through the second argument of the middleware function.
Signature:
originalState: T
: This argument represents the state before any middleware modifications.
Use Cases:
Determining State Diff: You can compare
currentState
withoriginalState
to see what changes have been made by previous middleware functions in the chain.Resetting to Original State: In certain conditions, you might want to discard the changes made by previous middleware and revert to the original state.
Conditional Logic: You can use the
originalState
to make decisions about how the middleware should behave based on the initial state of the application.
Example: "Blacklister" Middleware
Let's say you want to implement a middleware that prevents actions from modifying the state if it contains certain blacklisted words.
Explanation:
isBlacklisted
Function: A helper function that checks if a given text contains any blacklisted words.if (isBlacklisted(currentState.present.someTextProperty))
: We check if the relevant property in thecurrentState
contains any blacklisted words.return originalState;
: If a blacklisted word is found, we return theoriginalState
, effectively discarding any changes made by previous middleware or the action itself.return currentState;
: If no blacklisted words are found, we return thecurrentState
, allowing the middleware chain to continue.
Last updated
Was this helpful?