Hi,
I’m new using Netlify functions, I’m using Gatsby with Sanity on Netlfy. I’m trying to use function for user to post new job into sanity using Netlify function. I’ve started setting up a test form but I’m struggling to get everything working together.
Here my form using formik with yup:
const jobPostSchema = Yup.object().shape({
title: Yup.string()
.min(2, 'Too Short!')
.max(50, 'Too Long!')
.required('Job title is required.'),
email: Yup.string()
.email('Invalid email address')
.required('Email is required!'),
})
const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
}
export default class NewJob extends React.Component {
render() {
return (
<Layout>
<ContentWrapFull>
<PageHeading>Post a job</PageHeading>
<Formik
initialValues={{ title: '', email: '' }}
validationSchema={jobPostSchema}
onSubmit={(payload, { setSubmitting }) => {
fetch('/?no-cache=1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: encode({ 'form-name': 'jobsubmit', payload }),
})
alert(payload.title)
console.log(payload)
setSubmitting(false)
}}
>
{({
values,
errors,
dirty,
touched,
handleChange,
handleBlur,
handleSubmit,
handleReset,
isSubmitting,
/* and other goodies */
}) => (
<form
name="jobsubmit"
method="post"
action="/thanks/"
data-netlify="true"
onSubmit={handleSubmit}
>
<p>
<FormLabel>
Job position*
<br />
<FormInput
type="text"
name="title"
onChange={handleChange}
onBlur={handleBlur}
value={values.title}
/>
{errors.title && touched.title && errors.title}
</FormLabel>
</p>
<p>
<FormLabel>
Application Email or URL
<br />
<FormInput
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
/>
{errors.email && touched.email && errors.email}
</FormLabel>
</p>
<button
type="button"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
)}
</Formik>
</ContentWrapFull>
</Layout>
)
}
}
Here my function:
const sanityClient = require('@sanity/client')
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
})
const client = sanityClient({
projectId: 'idnumber',
dataset: 'databasename',
token: process.env.SANITY_TOKEN_WRITE,
})
exports.handler = async function(event, context, callback) {
let payload = JSON.stringify(event.body).payload
let result = await client.create({ _type: 'job', ...payload })
callback(null, {
statusCode: 200,
body: JSON.stringify(result),
})
console.log(data)
}
Any suggestion would be welcome, thank you.