Fix the replay of a memoized submit handler

Review the AI's codeEasy10 min

Your task

A form's Save button sends the old values after the user edits them. The submit handler was wrapped in useCallback with an empty dependency list, so it kept the form from the first render. useCallback returns the same function on every render until a value in its dependency list changes. The team wants a replay that compares three ways to capture the form.

An assistant wrote submit_outcome(form_values, invoke_at_render, capture_mode). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • form_values: the form's value on each render, as strings, in render order. Index 0 is the first render. It can be empty.
  • invoke_at_render: the index of the render at which the user presses Save. It can be negative or past the end.
  • capture_mode: "empty-deps", "form-deps" or "ref". Other strings can appear.
  • Return a list of two strings: the value the handler sends, then its identity, which is "stable", "changed" or "unknown".

Rules the tests check:

  • Check the mode first. Any mode other than the exact three returns ["", "unknown"].
  • An empty form_values returns ["", "stable"].
  • Clamp invoke_at_render into the list: below 0 becomes 0, past the end becomes the last index. Call the result r.
  • "empty-deps": the dependency list is []. The handler keeps the first render's form. Return the value at index 0 and "stable".
  • "ref": the handler reads a ref that is updated on every render. Return the value at index r and "stable".
  • "form-deps": the dependency list is [form]. The handler sends the value at index r.
  • With "form-deps", the handler is rebuilt at render i when the value at i differs from the value at i minus 1. Values compare as exact strings. Its identity is "changed" if it was rebuilt at any render from 1 to r, inclusive, and "stable" otherwise.

Examples

submit_outcome(form_values: list[str], invoke_at_render: int, capture_mode: str) -> list[str]
Example 1
Inputsubmit_outcome(["", "Ada", "Ada Lovelace"], 2, "empty-deps")
Output["", "stable"]
Example 2
Inputsubmit_outcome(["", "Ada", "Ada Lovelace"], 2, "form-deps")
Output["Ada Lovelace", "changed"]
Example 3
Inputsubmit_outcome(["", "Ada", "Ada Lovelace"], 2, "ref")
Output["Ada Lovelace", "stable"]