Making our app history-aware
To properly update the state history when dispatching actions, you need to make your actions "history-aware." This means that instead of returning a new State object, your actions should return a new StateHistory<State> object.
The Aurelia Store plugin provides a helper function called nextStateHistory to simplify this process:
// actions.ts
import { nextStateHistory, StateHistory } from 'aurelia-store';
import { State } from './state';
export const addFramework = (
currentState: StateHistory<State>,
frameworkName: string
): StateHistory<State> => {
const newPresentState: State = {
...currentState.present,
frameworks: [...currentState.present.frameworks, frameworkName],
};
return nextStateHistory(currentState, newPresentState);
};Explanation:
currentState: StateHistory<State>: The action now receives the entireStateHistoryobject as its first argument.newPresentState: State: We create a newStateobject representing the new present state, as we would normally do in a non-history-aware action.return nextStateHistory(currentState, newPresentState);: We use thenextStateHistoryhelper function to create a newStateHistoryobject. This function does the following:Moves the current
presentstate to thepastarray.Sets the
newPresentStateas the newpresentstate.Clears the
futurearray.
Manual Approach (not recommended):
You could manually create the StateHistory object, but it's more verbose and error-prone:
It's highly recommended to use the nextStateHistory helper function to ensure that the history is updated correctly.
Last updated
Was this helpful?