Skip to content
intermediate

Review: a reducer that mutates, and a UI that stops updating

This is recall. The code looks finished and is wrong. Find the defect and fix it. You are graded on tests you cannot see.

You asked a model for a todos reducer: add, toggle, clear completed. It produced this, with tests. The tests pass, and the data is always correct.

export interface Todo {
  id: number
  title: string
  done: boolean
}

export type TodosAction =
  | { type: 'add'; id: number; title: string }
  | { type: 'toggle'; id: number }
  | { type: 'clear-completed' }

export function todosReducer(state: Todo[], action: TodosAction): Todo[] {
  switch (action.type) {
    case 'add':
      state.push({ id: action.id, title: action.title, done: false })
      return state
    case 'toggle': {
      const todo = state.find((t) => t.id === action.id)
      if (todo) todo.done = !todo.done
      return state
    }
    case 'clear-completed': {
      for (let i = state.length - 1; i >= 0; i--) {
        if (state[i].done) state.splice(i, 1)
      }
      return state
    }
  }
}
review — find the defectCtrl+↵ submits · Ctrl+Shift+↵ runsstarter code