Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

hello! how to update form values with provided object in React Hook Form?

  1. User

    hello! how to update form values with provided object in React Hook Form?

  2. Assistant

    You can use the reset method provided by React Hook Form to update the form values with a provided object.

    Here's an example:

    import React from 'react';
    import { useForm } from 'react-hook-form';
    
    const MyForm = () => {
      const { register, handleSubmit, reset } = useForm();
    
      const onSubmit = (data) => {
        console.log(data);
      };
    
      const updateFormValues = () => {
        const newData = {
          firstName: 'John',
          lastName: 'Doe',
          email: 'john.doe@example.com',
        };
        reset(newData);
      };
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <input type="text" name="firstName" ref={register} />
          <input type="text" name="lastName" ref={register} />
          <input type="email" name="email" ref={register} />
          <button type="submit">Submit</button>
          <button type="button" onClick={updateFormValues}>Update Form Values</button>
        </form>
      );
    };
    
    export default MyForm;
    

    In the example above, the updateFormValues function is called when the "Update Form Values" button is clicked. It creates a new object with updated values, and passes it to the reset method to update the form values.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.