Skip to content

Conversation

@KATT
Copy link
Owner

@KATT KATT commented Mar 29, 2024

Evening-hack alternative to useActionState() / useFormState()

Demo: disable JavaScript and put "john" into the input at https://react-server-action-useformstate-issues-git-feat-hack-katt.vercel.app/

Summary

  • Background: see the README of the main-branch
  • No notion of "default state" when calling the hook
  • No need of returning input values in order to re-render <input>s values in SSR
  • Not 2 arguments on actions, there's only 1 - your input

What we're missing here

This work is mainly focused on enhancing the "no-JS-experience":

  • <form>'s should clear after submission in JS
  • payload is always null in the client, will be more highlighted when form clears in JS as well
  • payload isn't tied to a specific action at the moment - useAction(x) shouldn't return payload of useAction(y)
  • this is a hack, there's probably more

API

function useAction<State, Payload extends FormData>(
	action: (state: Awaited<State>, payload: Payload) => State,
	permalink?: string,
): [
	/**
	 * The action to use in a `<form>` element.
	 */
	dispatch: (payload: Payload) => State,
	/**
	 * Will be `null` if no payload is available.
	 */
	payload: null | Payload,
	/**
	 * Will be `null` if no state is available.
	 */
	state: Awaited<State> | null,
];

Usage

Setting it up

Obviously, I don't think any of this wiring should be needed and that payload should be omnipresent in useFormState()

Yay, now I can just use input?.get("username"):

defaultValue={input?.get("username") as string}

How this hack works

  • createAction() wrapper hacks into Next.js' request storage and stores an .actionPayload with the submitted FormData (omitting File-fields as they aren't serializable)
  • <UseActionProvider> is used to populate this to the useAction() handler

Play with it

git clone [email protected]:KATT/react-server-action-useActionState-useFormState-issues.git
cd react-server-action-useActionState-useFormState-issues
git checkout feat/hack
pnpm i
pnpm dev

@vercel
Copy link

vercel bot commented Mar 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
react-server-action-useformstate-issues ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 4, 2024 4:19pm

@KATT KATT changed the title hacky wip: make a useAction()-hook that I like better Mar 29, 2024
# Conflicts:
#	package.json
#	pnpm-lock.yaml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants