Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Todo Add Reducer

Reducersmedium

Course · Section 17: Modern JavaScript Development: Modules, Tooling, and Functional · Lecture 294: Declarative and Functional JavaScript Principles

Implement `todoAddReducer(state, action)` where `state` is an array of todos and an `add` action carries `text`. Append `{ text, done: false }` immutably. Unknown actions return state unchanged.

Sample tests

Input: todoAddReducer([], {"type":"add","text":"x"})
Output: [{"text":"x","done":false}]
Input: todoAddReducer([{"text":"a","done":false}], {"type":"add","text":"b"})
Output: [{"text":"a","done":false},{"text":"b","done":false}]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • state.push(...) mutates the array.
  • Returning a new array for unrelated action types causes needless re-renders.

Learning resources

  • React: useReducer
Approach & explanation (try first)

For an add action, return a new array spreading the old todos plus the new { text, done: false }. Other actions return the same array reference unchanged.

Loading...
⌘/Ctrl + Enter

Run your code to see results.