form-atoms / form-atoms

Atomic form primitives for Jotai

Home Page:https://codesandbox.io/s/getting-started-with-form-atoms-v2-ddhgq2?file=/src/App.tsx

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

onReset callback

schiller-manuel opened this issue · comments

I'd like to react to a form reset by supplying e.g. an onReset callback that is executed after a form was reset.
Is this already possible?

My concrete use case is an atom that holds display state of the form, but is not part of the form state itself. I'd like to be able to set this atom upon form reset. I did not put into the form state since modifying just the form display state should not cause the form state to be dirty.

Can't you use the native onReset event? https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset_event

import { flushSync } from 'react-dom';
...

           <form
              onSubmit={form.submit(async (values) => {
                  await onSubmit(values, formActions);
              })}
              onReset={(event) => {
                flushSync(() => {
                  form.reset();
                 })
                 
                onReset?.(event);
              }}
              {...elementProps}
            >
              {typeof children === "function"
                ? children(form.fieldAtoms, formActions)
                : children}
            </form>

Or can you do something with derived state? https://jotai.org/docs/guides/composing-atoms#basic-derived-atoms

How would the onReset form event be triggered if I reset the form like this:

const formActions = useFormActions(formAtom);
formActions.reset();

I would personally use a native form reset. But to accomplish it programmatically, it's the same:

flushSync(() => {
  formActions.reset()
})
                 
onReset();

That is, I don't see why this is needed in the library. You can just invoke the reset thing you're doing when you invoke the reset. Or use Jotai's derived state patterns.

It is not needed, it would be nice to have. I have a component that listens to the dirty state of the form atom and displays save/discard buttons in case the form is dirty. When the discard button is clicked, the form is reset via formActions.reset().
Currently I have to prop drill the onReset callback to that component.
If the formAtom would execute it upon reset, the component would not need to be made aware of it.

There are ways to solve this with React/Jotai (prop drilling, as you mentioned is one). Minor inconveniences are perfectly OK in software engineering and do not necessitate unnecessary abstractions (as my GitHub bio has trumpeted for years 😏)