Subscribing to the stream of states
Once you have configured the Aurelia Store plugin, you can start subscribing to the stream of states in your components. This allows your components to react to changes in the application's state and update their UI accordingly.
Injecting the Store
To access the store in your component, you need to inject it using Aurelia's dependency injection.
Explanation:
import { inject } from 'aurelia-dependency-injection';
: Imports theinject
decorator from Aurelia's dependency injection library.import { Store } from 'aurelia-store';
: Imports theStore
class from the Aurelia Store plugin.@inject(Store)
: This decorator tells Aurelia to inject an instance of theStore
into your component's constructor.constructor(private store: Store<State>) {}
: The constructor receives the injectedStore
instance. Theprivate
keyword automatically creates a property calledstore
on your component and assigns the injected store to it.
Creating a Subscription
The recommended place to subscribe to the state is in the bind
lifecycle method of your component.
Explanation:
bind() { ... }
: Thebind
lifecycle method is called when the component is attached to the DOM and its data bindings are ready.this.subscription = this.store.state.subscribe(...)
:this.store.state
accesses theObservable
that emits the stream of states..subscribe(...)
subscribes to theObservable
, which means that the provided callback function will be executed every time a new state is emitted.The subscription is assigned to
this.subscription
so that we can unsubscribe later.
(newState: State) => this.state = newState
: This is the callback function that is executed for each new state. It simply assigns the new state to the component'sstate
property.
Disposing of the Subscription
It's important to unsubscribe from the state when the component is unbound (e.g., when it's removed from the DOM). This prevents memory leaks. You should do this in the unbind
lifecycle method.
Explanation:
unbind() { ... }
: Theunbind
lifecycle method is called when the component is detached from the DOM.this.subscription.unsubscribe();
: This unsubscribes from the stateObservable
, preventing the callback function from being executed anymore.
Consuming the State in the Template
Now that your component has access to the state and updates it whenever a new state is emitted, you can use the state directly in your template:
Explanation:
state.frameworks
: This accesses theframeworks
array from the current state object.repeat.for="framework of state.frameworks"
: This Aurelia repeater iterates over theframeworks
array and creates a list item for each framework.
With this setup, your component will automatically re-render whenever the frameworks
array in the state changes.
Last updated
Was this helpful?