Closed fsgreco closed 5 years ago
I manage to get it working with some help from stackoverflow. This is the final result (I was lacking an encode function to pass the values as a string through the netlify API), so the only changes are to place a function encode at the top and the encode the values on the submit data that you send to netlify:
[...]
import SEO from "../components/seo"
function encode(data) {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}
const ContactForm = () => (
[...]
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": "formik",
...values
})
[...]
@anonimoconiglio
I'm doing the same but for some reasons, I'm not able to post to Netlify. I've checked your code and pretty much the same as mine.
I'm struggling to debug the problem. Maybe you can point me in the right direction?
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { navigate } from 'gatsby';
const schema = Yup.object().shape({
name: Yup.string()
.min(3, 'Too Short!')
.max(50, 'Too Long!')
.required('Name is required'),
email: Yup.string()
.email('Invalid email')
.required('Email is required'),
});
function encode(data) {
return Object.keys(data)
.map(
key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
)
.join('&');
}
const FirstExample = () => (
<Formik
initialValues={{ name: '', email: '', message: '' }}
validationSchema={schema}
onSubmit={values => {
fetch('/contact', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: encode({
'form-name': 'contact',
...values,
}),
})
.then(navigate('/thanks'))
.catch(error => alert(error));
}}
>
{({ isSubmitting }) => (
<Form name="contact" data-netlify="true" action="/thanks">
<input type="hidden" name="form-name" value="contact" />
<div className="form-control">
<label htmlFor="name">Name</label>
<Field type="text" name="name" />
<ErrorMessage name="name" />
</div>
<div className="form-control">
<label htmlFor="email">Email</label>
<Field type="email" name="email" />
<ErrorMessage name="email" />
</div>
<div className="form-control">
<label htmlFor="message">Message</label>
<Field component="textarea" rows="8" name="message" />
</div>
<button className="button inverse" type="submit">
Submit
</button>
</Form>
)}
</Formik>
);
export default FirstExample;
I managed to configure everything as expected with Formik, and the ajax requests shows me the success message, but the netlify form section is still empty (even if the form is listed and aknowledged by netlify).
This is my contact component: