0
0
Angularframework~30 mins

NgRx store concept in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
NgRx Store Concept
📖 Scenario: You are building a simple Angular app to manage a list of favorite fruits. You want to use NgRx store to keep the list in a central place so different parts of your app can access and update it easily.
🎯 Goal: Create a basic NgRx store setup to hold a list of fruits, add a configuration for the initial state, write a reducer to handle adding a fruit, and complete the store module setup in your Angular app.
📋 What You'll Learn
Create an initial state object with a fruits array
Add a configuration variable for the initial state
Write a reducer function to handle adding a fruit to the fruits array
Complete the NgRx StoreModule setup in the Angular app module
💡 Why This Matters
🌍 Real World
NgRx store helps manage app state in large Angular apps, making data flow predictable and easier to debug.
💼 Career
Understanding NgRx store is important for Angular developers working on scalable, maintainable applications with complex state.
Progress0 / 4 steps
1
Create initial state
Create a constant called initialState with an object that has a property fruits set to an empty array.
Angular
Need a hint?

Think of initialState as the starting point for your fruit list in the store.

2
Add initial state configuration
Create a constant called fruitFeatureKey and set it to the string 'fruit' to identify this feature in the store.
Angular
Need a hint?

This key helps NgRx know which part of the store holds your fruit data.

3
Write reducer to add fruit
Write a reducer function called fruitReducer that takes state and action parameters. Use a switch on action.type. When the type is 'addFruit', return a new state with the fruits array including the new fruit from action.payload. For default, return the current state.
Angular
Need a hint?

The reducer updates the state based on the action type. Here, it adds a new fruit to the list.

4
Complete StoreModule setup
In your Angular module file, import StoreModule from @ngrx/store. Then add StoreModule.forRoot({ [fruitFeatureKey]: fruitReducer }) to the imports array of your @NgModule decorator.
Angular
Need a hint?

This step connects your reducer to the Angular app so the store works globally.