Bird
0
0

You want to create a feature state slice named 'user' with initial state { name: '', loggedIn: false }. Which is the correct way to define the reducer using NgRx createReducer?

hard📝 component behavior Q8 of 15
Angular - State Management
You want to create a feature state slice named 'user' with initial state { name: '', loggedIn: false }. Which is the correct way to define the reducer using NgRx createReducer?
Aconst userReducer = createReducer( { name: '', loggedIn: false }, on(login, (state) => { state.loggedIn = true; return state; }), on(logout, (state) => { state.loggedIn = false; return state; }) );
Bconst userReducer = createReducer( on(login, state => ({ ...state, loggedIn: true })), on(logout, state => ({ ...state, loggedIn: false })) );
Cconst userReducer = createReducer( { name: '', loggedIn: false }, login(state) { return { ...state, loggedIn: true }; }, logout(state) { return { ...state, loggedIn: false }; } );
Dconst userReducer = createReducer( { name: '', loggedIn: false }, on(login, state => ({ ...state, loggedIn: true })), on(logout, state => ({ ...state, loggedIn: false })) );
Step-by-Step Solution
Solution:
  1. Step 1: Recall createReducer syntax

    createReducer takes initial state first, then on() handlers for actions.
  2. Step 2: Check immutability in handlers

    Handlers must return new state objects without mutating existing state.
  3. Step 3: Compare options

    const userReducer = createReducer( { name: '', loggedIn: false }, on(login, state => ({ ...state, loggedIn: true })), on(logout, state => ({ ...state, loggedIn: false })) ); correctly uses initial state, on() handlers, and returns new objects.
  4. Final Answer:

    const userReducer = createReducer( { name: '', loggedIn: false }, on(login, state => ({ ...state, loggedIn: true })), on(logout, state => ({ ...state, loggedIn: false })) ); -> Option D
  5. Quick Check:

    createReducer needs initial state and pure on() handlers [OK]
Quick Trick: createReducer needs initial state and pure on() handlers [OK]
Common Mistakes:
  • Omitting initial state
  • Mutating state inside handlers
  • Using incorrect handler syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes