Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method to update custom context after the form initialisation? #11823

Closed
nicostombros opened this issue Apr 26, 2024 · 0 comments
Closed

Method to update custom context after the form initialisation? #11823

nicostombros opened this issue Apr 26, 2024 · 0 comments
Labels
feature request request a feature to be added waiting-up-vote Waiting for votes from the community.

Comments

@nicostombros
Copy link

Problem
I have a situation where I have the following code

const [additionalFields, setAdditionalFields] = useState<Field[]>()

const form = useForm({
  resolver: yupResolver(schema),
  defaultValues: {
    name: instance.name,
    material: instance.material,
    process: instance.process,
  },
  context: {
    additionalFields: additionalFields.map(a => a.name),
  }
})

...

<MySubForm control={form.control} setAdditionalFields={setAdditionalFields} />

As you can see, I have some state, a form initialised with useForm and a component that uses the setter to pass UP the additional fields to be set, which is then used in the form context. I was wondering if there's a neater way to set some context? Since I'm constantly doing this bidirectional dance with the flow of data — I'd rather have some way to use the form in MySubForm to then set the context there instead of having the state lifted up to the parent form.

Potential solution
Something like where in the MySubForm component I could do

const MySubForm = ({ form }) => {
  function additionalFieldsChange (additionalFields) {
    form.updateContext({ additionalFields: additionalFields.map(a => a.name) })
  }
}

Use cases
I feel this would be super useful for subforms to be able to interact/update the form themselves rather than having a lot of setters that propagate to the parent form component, as is such in my codebase.

@nicostombros nicostombros added feature request request a feature to be added waiting-up-vote Waiting for votes from the community. labels Apr 26, 2024
@bluebill1049 bluebill1049 added this to Pending Feature Requests in React Hook Form May 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request request a feature to be added waiting-up-vote Waiting for votes from the community.
Projects
React Hook Form
  
Pending Feature Requests
Development

No branches or pull requests

2 participants