SiiilverSurfer
SiiilverSurfer

Reputation: 959

How do I perform a POST request only when form is validated with react-hook-form?

I want to create a contact form using FlexyForm in my Gatsby project in order to send the info by email. The setup for it is very simple and you just need to add to a normal form HTML tag - method="post" action="https://www.flexyform.com/f/flexyformkey"

So I had a form like this that was functioning and then I wanted to add form validation so I used react-hook-form and the validation works great but after validating it doesn't make the post request to FlexyForm.

I fill the form to satisfy the validation and hit send button but other than logging the register to the console nothing happens. Without react-hook-form it usually redirects me to wherever I set FlexyForm to redirect after receiving data.

sandbox: https://codesandbox.io/s/nervous-pine-o2z5m (^^ it doesn't include the key for obvious reasons)

I later figured that I should use fetch to make a post request inside onSubmit but I'm not sure what to put inside it.

I'm quite new to React and Gatsby so it might be something obvious I'm missing.

Upvotes: 1

Views: 3859

Answers (1)

Abdullah KOCAKAYA
Abdullah KOCAKAYA

Reputation: 71

Yes, you should use fetch in onSubmit. Try this.

const onSubmit = async (data) => {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    };

    const response = await fetch([URL_IS_HERE], requestOptions);
    const jsonData = await response.json();

    console.log(jsonData);
}

Upvotes: 3

Related Questions