ngrx: easy debugging with example
Debugging is an important aspect of any application development process, and it becomes more critical when we work with complex state management libraries like ngrx. In this example, I’ll show you how to enable easy debugging in ngrx by using the ngrx-store-logger middleware.
To enable easy debugging in ngrx, we can use the ngrx-store-logger middleware. This middleware logs every action dispatched, the current state before and after each action, and the time taken to process each action. This makes it easy to see what’s happening in the store and debug any issues that may arise.
Here’s an example of how we can add the ngrx-store-logger middleware to our ngrx store:
import { ActionReducer, MetaReducer, ActionReducerMap } from '@ngrx/store';
import { storeLogger } from 'ngrx-store-logger';
export function logger(reducer: ActionReducer<any>): ActionReducer<any> {
return storeLogger()(reducer);
}export const metaReducers: MetaReducer<any>[] = [logger];
In this code snippet, we define a logger
function that takes an ActionReducer
and returns an ActionReducer
. The returned function is the ngrx-store-logger middleware, which takes no arguments.
Next, we create an array of MetaReducer
s and add our logger
function to it. We can then use this array when we create our store:
import { StoreModule } from '@ngrx/store';
import { metaReducers } from './reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, { metaReducers })
]
})
export class AppModule { }
In this code snippet, we import the metaReducers
array from our reducers file and pass it to the forRoot
method of the StoreModule
. This enables the ngrx-store-logger middleware in our store.
With this middleware enabled, we can open the browser console and see detailed logs of every action and state change that occurs in our store. For example, when we dispatch an action, we can see a log like this:
prev state {user: null}
action LoadUser
next state {user: {id: 1, name: 'John'}, loading: false, error: ''}
This log shows the previous state of the store, the action that was dispatched, and the next state of the store after the action was processed. It also shows the time taken to process the action.
By enabling the ngrx-store-logger middleware, we can easily debug our ngrx store and ensure that it’s behaving as expected
BONUS BELOW
If you are new to the web development and hustling for bread and butter due to low income, Please check out the below link
Live Chat Jobs — You have to try this one at home