React Foundations ยท Actions & Forms

Reading the result of an action

useActionState

Reading the result of an action

A form action returns a value, but a plain <form action> throws that value away. useActionState is how you keep it. It wraps your action and hands back the latest result, a wrapped action to pass to the form, and a pending flag:

const [state, formAction, isPending] = useActionState(action, initialState);

The wrapped formAction goes straight onto the form:

<form action={formAction}>
  <input name="name" />
  <button type="submit">Greet</button>
  <p>{state}</p>
</form>

Your action takes the previous state first, then the FormData, and returns the next state:

function action(previousState, formData) {
  return `Hello ${formData.get('name')}`;
}

That first argument is what lets one call build on the last: each action sees the result of the previous one. The action may be async. If it returns a promise, isPending is true from submit until the promise settles, so you can disable the button or show a spinner.

Your job is to hold the action's result in useActionState in App.jsx and render it.

Challenge

A greeting form shows nothing until it is submitted, and its result should survive the round trip. Export an App component from App.jsx that keeps its result in useActionState. The action returns Hello <name> from the form's name field, and the initial state is Hello stranger. Show the state in a paragraph inside a form whose action is the wrapped action, with a text input named name and a submit button labelled Greet.

The Test expects Hello stranger before you submit, then types Ada, submits, and expects Hello Ada. The starter never updates, so the Test fails.

App.jsx
export function App() {
  return (
    <form aria-label="Greeting">
      <input name="name" />
      <button type="submit">Greet</button>
      <p>Hello stranger</p>
    </form>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.