Registering the root state
A reminder that the state of an application managed by store is just one large object. The reducer function which we write only manages parts of the state.
Registering reducer functions to manage parts of your state only define keys with associated values in the object.
Hence, we need to register the global Store of our application, for this use StoreModule.forRoot() method with a map of key/value pairs that define the state.
The StoreModule.forRoot() registers the global providers for an application, including the Store service you inject into your components and services to dispatch actions and select pieces of state.
Registering states with StoreModule.forRoot() ensures that the states are defined upon application startup. In general, register root states that always need to be available to all areas of your application immediately.
@NgModule({
imports: [
StoreModule.forRoot({todoState: todoReducer})
],
})
export class AppModule {
}
Cleanup to make our fully managed by NgRx
We don’t need to perform add, update, and delete on component. So, let’s remove those things to make it fully state-managed.
However, after removing those things, you will notice that there will be no change in UI. That is because we are only updating on state, but we are not listening or subscribing to state changes.
export class TodoComponent implements OnInit {
undoOrCompleteTodo(item: Todo) {
const todo: Todo = {...item, done: !item.done};
this.store.dispatch(saveOrUpdateTodo({todo, isUpdate: true}));
}
deleteTodo(todoId: number) {
this.store.dispatch(deleteTodo({todoId}))
}
addTodo(): void {
if (this.todoIdFormControl.value && this.todoIdFormControl.value >= 0 && !this.todos.find(t => t.id === this.todoIdFormControl.value)) {
const todo: Todo = {
id: this.todoIdFormControl.value,
description: this.todoDescriptionFormControl.value ?? '',
done: false
}
this.store.dispatch(saveOrUpdateTodo({todo, isUpdate: false}));
}
}
}
Verify changes
- Right click on the application browser and go to inspect.
- Now Redux tab should be available.
- Play around the application and the devtools state should change accordingly.
We will later look at how to lazily load the store using StoreModule.forFeature().