Shared context and request

In this module we implement a form.

We will keep it simple to focus more on the differences between the various implementations (useState, useReducer, and state machine).

The <form> contains a single "username" <input> field and a "submit" <button>. We will implement the logic to store the username in context and send an async request.

Like this:

export default function Page() {
  // State logic here

  return (
    <form onSubmit={(event) => {
      // Submit form (async request) here
    }}>
      <input
        type="text"
        value={/* Value here */}
        onChange={(event) => {
          // Update context value here
        }}
      />
      <button
        disabled={/* Disabled when sending request */}
      >
        Confirm
      </button>
    </form>
  );
}

Shared code between all implementations

This time we will start by extracting the shared code between all implementations in a separate file.

All implementations share the same context type and initial value, as well as the same async request function:

export interface Context {
  username: string;
}

export const initialContext: Context = { username: "" };

// 👇 Mock implementation of async request
export const postRequest = (context: Context) =>
  new Promise<Context>((resolve) =>
    setTimeout(() => {
      resolve(context);
    }, 1000)
  );

All this code is the same in all implementations, regardless of the state management strategy we use.

All examples will reference this shared file, so that we can focus more on the differences.

Remainder: you will get the most out of the course by following along with the examples, therefore I suggest you to clone the repository 👇

Github repository