name: The name of the state slice. Note: The name is a required parameter and must be unique for the entire application.
defaults: Default set of object/array for this state slice.
children: Child sub state associations.
nameof your state with a state token:
@Actiondecorator. The action decorator accepts an action class or an array of action classes.
FeedAnimalsaction to toggle whether the animals have been fed:
feedAnimalsfunction has one argument called
ctxwith a type of
StateContext<ZooStateModel>. This context state has a slice pointer and a function exposed to set the state. It's important to note that the
getState()method will always return the freshest state slice from the global store each time it is accessed. This ensures that when we're performing async operations the state is always fresh. If you want a snapshot, you can always clone the state in the method.
patchStatefunction to make updating the state easier. In this case, you only pass it the properties you want to update on the state and it handles the rest. The above function could be reduced to this:
setStatefunction can also be called with a function which will be given the existing state and should return the new state. All immutability concerns need to be honoured by this function.
setStatefunction... With a new constructed state value:
state operatorsso that your code can become more declarative as opposed to imperative. You can find more details in our state operators documentation.
state operatorsthrough their curried
producefunction. Here is the example from above expressed in this way:
producefunction from the
immerlibrary is called with just a single parameter so that it returns its curried form that will take a value and return a new value with all the expressed changes applied.
feedand then call
setStatewith the result. Remember that we can guarantee that the state is fresh since the state property is a getter back to the current state slice.
tap. If we return the Observable, the framework will automatically subscribe to it for us, so we don't have to deal with that ourselves. Additionally, if we want the stores
dispatchfunction to be able to complete only once the operation is completed, we need to return that so it knows that.
dispatchfunction that is contained in the state context object.