Subscribe to field changes outside react #9957
Unanswered
shkreios
asked this question in
Show and tell
Replies: 2 comments 8 replies
-
Thanks for sharing such a solution! |
Beta Was this translation helpful? Give feedback.
2 replies
-
Some ideas for API:
const { getFormState } = useForm()
getFormState(); // return current form state
getFormState({
dirtyFields: true,
name: 'test'
}).subscribe((formState) => {
console.log(formState)
})
import { createFormControl } from '@hookform/core'
const formControl = createFormControl();
formControl.getFormState().subscribe()
function Test() {
const { formstate } = useForm({
control: formControl,
})
return null;
} |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Prerequisites
This may be a purely over optimized solution just to reduce the number of react re-renders. It also uses undocumented and not simver following internal
react-hook-form
apis. So use it at your own risk.Introduction
In my use case I have a large configurable invoicing editor for which I wanted to use
react-hook-form
on input side and@react-pdf/renderer
for the live preview. Think of a split screen where the left side is the input form and the right side is a pdf preview. Since both pages need to calculate some additional properties from the inputs, such as net amount, tax, etc., and I already usedzustand
throughout the application, I wanted to synchronizereact-hook-form
with thezustand
store. As I already moved the pdf generation into a web worker, to keep the typing experience lag free, I wanted to also minimize any unnecessary renders.But now to the most important thing, this is what interfacing with this new hook looks like:
Installation
Examples
Usage
Features/Benefits
useCallback
, but also doesn't resubscribe on each render with the help ofuseEvent
Use cases
react-hook-form
state in real-time with any apireact-hook-form
fieldsreact-hook-form
with other state libraries e.g.zustand
Pretty much a imperative version of the
useWatch
hookImplementation
startsWith.ts
useFormSubscribe.ts
Experimental tracked option
Instead of string paths, this option uses proxy objects to determine which field has been accessed and thus needs to be subscribed to.
CAUTION the current proxy implementation calls the subscribe function for the first time if any fields changes and only track the accessed properties in this first call and subsequent calls will not be tracked
Experimental tracked implementation
Would love to here some feedback
Thanks have a great day 🙂
Beta Was this translation helpful? Give feedback.
All reactions