Consider this Angular reducer function handling a counter state. What will be the new state after dispatching the action { type: 'increment' } when the current state is { count: 5 }?
function counterReducer(state = { count: 0 }, action: { type: string }) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } } const currentState = { count: 5 }; const newState = counterReducer(currentState, { type: 'increment' }); console.log(newState);
Think about what the reducer does when it receives the 'increment' action.
The reducer adds 1 to the current count when the action type is 'increment'. Starting from 5, it returns 6.
Choose the correct syntax for an action creator function that returns an action object with type 'addItem' and a payload containing an item string.
Look for the standard keys used in action objects.
Actions typically have a 'type' key and a 'payload' key for data. Option B follows this pattern correctly.
Examine the reducer code below. Why will it cause an error when dispatched with any action?
function todoReducer(state = [], action: { type: string, payload?: string }) { switch (action.type) { case 'add': state.push(action.payload); return state; default: return state; } }
Reducers should never change the original state directly.
Reducers must return a new state object without mutating the existing state. Using push changes the original array, which breaks this rule.
Given the reducer and the sequence of dispatched actions below, what is the final state?
function counterReducer(state = { count: 0 }, action: { type: string }) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; case 'reset': return { count: 0 }; default: return state; } } let state = { count: 0 }; state = counterReducer(state, { type: 'increment' }); state = counterReducer(state, { type: 'increment' }); state = counterReducer(state, { type: 'decrement' }); state = counterReducer(state, { type: 'reset' }); state = counterReducer(state, { type: 'increment' }); console.log(state);
Follow each action step by step and update the count.
The count goes 0 → 1 → 2 → 1 → 0 → 1 after each action respectively.
Choose the most accurate description of what actions do in the actions and reducers pattern in Angular.
Think about the purpose of actions as messages.
Actions are plain objects that describe events and carry any needed data. They do not modify state themselves but tell reducers what to do.