I am trying to use NGRX redux library with Angular 12. The state of the application is undefined.
Index.ts
export interface ApplicationState {
product: ProductState | undefined;
}
export const reducers: ActionReducerMap<ApplicationState> = {
product: productReducer,
};
export const metaReducers: MetaReducer<ApplicationState>[] = [];
App.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
AppRoutingModule,
StoreModule.forRoot(reducers, { metaReducers })
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Reducer
export interface ProductState {
formValidation: FormGroup;
}
export const initialState: ProductState = {
formValidation: new FormGroup({})
};
export const productReducer: any = (state: ProductState | undefined, incomingAction: Action): ProductState => {
if (state === undefined) {
return state;
}
const action = incomingAction as KnownAction;
switch (action.type) {
case 'FORM_VALIDATION':
return state;
default:
return state;
}
};
Action
export interface ProductFormValidationAction { type: 'FORM_VALIDATION' }
export type KnownAction = ProductFormValidationAction | any;
export const ActionCreators = {
formValidation: () => ({ type: 'FORM_VALIDATION' } as ProductFormValidationAction)
};
The state of the application is undefined on the reducer call, quite not sure what may be the main issue.
Dispatch Method
import {ActionCreators, GetUsers} from '../../store/action/product.actions'
constructor(
private store: Store<ApplicationState>
) { }
ngOnInit(): void {
this.store.dispatch(ActionCreators.formValidation());
}
You need to default state
to your initialState
.
export const proudctReducer = (state: ProductState = initialState, ...)