All quizzesEasy
Actions & Reducers
Preview — 3 of 10 questions
What is NgRx and what problem does it solve?
javascript
┌──────────────────────────────────────────────────────┐
│ NgRx Data Flow │
│ │
│ Component → dispatch(Action) → Reducer │
│ ↑ ↓ │
│ select(Selector) State (Store) │
│ ↑ ↓ │
│ Store ←←←←←←←←←← Effect (side effects/HTTP) │
└──────────────────────────────────────────────────────┘AA reactive state management library for Angular based on Redux principles, providing a centralized, predictable, and immutable store
BA CSS-in-JS library for Angular components
CA testing framework for Angular services and components
DA router extension that adds state to URL parameters
What is an NgRx action?
javascript
import { createAction, props } from '@ngrx/store';
// Simple action (no payload)
export const loadUsers = createAction('[Users Page] Load Users');
// Action with typed payload
export const loadUsersSuccess = createAction(
'[Users API] Load Users Success',
props<{ users: User[] }>()
);
export const loadUsersFailure = createAction(
'[Users API] Load Users Failure',
props<{ error: string }>()
);
// Dispatching from a component:
@Component({ standalone: true })
export class UsersPageComponent implements OnInit {
constructor(private store: Store) {}
ngOnInit() {
this.store.dispatch(loadUsers());
}
onRetry() {
this.store.dispatch(loadUsers());
}
}AA TypeScript class that extends NgModule
BA plain object with a type string property that describes an event in the application
CA function that directly modifies the state tree
DAn Observable that emits state changes
What is a reducer in NgRx?
javascript
import { createReducer, on } from '@ngrx/store';
export interface UsersState {
users: User[];
loading: boolean;
error: string | null;
}
export const initialState: UsersState = {
users: [],
loading: false,
error: null,
};
export const usersReducer = createReducer(
initialState,
on(loadUsers, state => ({
...state,
loading: true,
error: null,
})),
on(loadUsersSuccess, (state, { users }) => ({
...state,
loading: false,
users, // replace with new array
})),
on(loadUsersFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
);AA pure function that takes the current state and an action, and returns a new state object
BA service that fetches data and updates the store
CA directive that renders state values in the template
DA class that manages subscriptions to the store
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.