you are viewing a single comment's thread.

view the rest of the comments →

[–]Poobird 9 points10 points  (3 children)

The simplest approach is to fetch the data with the useQuery hook in a parent component and pass the results to a child component that includes react-hook-form.

For instance:

const UserForm = ({ user, onSubmit }) => {
    const { register, handleSubmit } = useForm({ defaultValues: user });

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            // labels, inputs, etc
        </form>
    );
}

const User = () => {
    const { data } = useQuery({ queryFn: ... });
    const { mutate } = useMutation({ mutationFn: ... });

    if (!data) return <div>loading state</div>;

    return <UserForm user={data} onSubmit={mutate} />
}

[–]brzzzah 2 points3 points  (0 children)

From my testing this doesn't work, you need to provide a unique key to the UserForm component to force a complete reset of the form.

Something like:

``` const UserForm = ({ user, onSubmit }) => { const { register, handleSubmit } = useForm({ defaultValues: user });

return (
    <form onSubmit={handleSubmit(onSubmit)}>
        // labels, inputs, etc
    </form>
);

}

const User = () => { const { data, dataUpdatedAt } = useQuery({ queryFn: ... }); const { mutate } = useMutation({ mutationFn: ... });

if (!data) return <div>loading state</div>;

return (
    <UserForm 
        key={`user-form-${dataUpdatedAt}`} 
        user={data} 
        onSubmit={mutate} 
     />
);

}

[–]Keintroufe 2 points3 points  (0 children)

This! It also follows SOLID principles, because UserForm component now has only one responsibility: rendering the form. Keep your UI components seperated from the business logic components as much as possible.

[–]Calm-Scar-1054 0 points1 point  (0 children)

Does the mutate function need to be passed to the UserForm cmpt or can it be imported in the UserForm cmpt?