Adam
Adam

Reputation: 1242

Next js API resolved without sending a response for /api/contact, this may result in stalled requests

Getting API resolved without sending a response for /api/contact, this may result in stalled request on the following API route in Next.js. It's using sendgrid and the email gets sent but I'm not getting a response back so I can handle errors or success message.

I've updated the below with the front end code. I'm now not getting that error but on the front end the call 'const response = await fetch('/api/contact'..' doesn't return anything

const sgMail = require('@sendgrid/mail');

sgMail.setApiKey(process.env.SENDGRID_APIKEY);

export default function handler(req, res) {
    if (req.method === 'POST') {
        const email = {
            from: process.env.EMAIL_FROM,
            to: process.env.EMAIL_TO,
            subject: 'Website Contact Form',
            html: `<div>
          <div><strong>Name:</strong> ${req.body.name}<br/></div>
          <div><strong>Phone:</strong> ${req.body.phone}<br/></div>
          <div><strong>Email:</strong> ${req.body.email}<br/></div>
          <div><strong>more:</strong> ${req.body.more}<br/></div>
        </div>`,
        };

        try {
            return sgMail
                .send(email)
                .then(() => {
                    console.log('res1', res);
                    //return res;
                    return res.status(200).end();
                })
                .catch((error) => {
                    console.log('error', error);
                    return res.status(500).send(error);
                });
        } catch (error) {
            console.log('error 2', error);
            res.json(error);
            return res.status(405).end();
        }
    }
}
import React from 'react';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';

import TextAreaField from './textAreaField';
import TextField from './textfield';

function ContactForm() {
    return (
        <Formik
            initialValues={{
                name: '',
                phone: '',
                email: '',
                more: '',
            }}
            validationSchema={Yup.object({
                name: Yup.string().required('Required'),
                phone: Yup.string().required('Required'),
                email: Yup.string().email('Invalid email address').required('Required'),
                more: Yup.string().required('Required'),
            })}
            onSubmit={async (values, { setSubmitting }) => {
                setSubmitting(true);
                const response = await fetch('/api/contact', {
                    body: JSON.stringify({
                        name: values.name,
                        phone: values.phone,
                        email: values.email,
                        more: values.more,
                    }),
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    method: 'POST',
                });
                console.log('response', response);
                const data = await response.json();
                console.log('response 1', data);
                setSubmitting(false);
            }}
        >
            {(props) => {
                const { values, setFieldValue } = props;
                console.log('props', props);
                console.log('values', values);
                return (
                    <div className="c-contact-form">
                        <Form className="form">
                            <TextField label="Customer Name" name="name" type="text" placeholder="John" />
                            <TextField label="Phone Number" name="phone" type="text" placeholder="07909765432" />
                            <TextField label="Email Address" name="email" type="email" placeholder="[email protected]" />
                            <TextAreaField label="More" name="more" placeholder="More details" />
                            <button type="submit" className="c-btn">
                                Submit
                            </button>
                        </Form>
                        {values.success && (
                            <div>
                                <p>Your enquiry has been successfully submitted.</p>
                            </div>
                        )}
                        {values.nosend && (
                            <div>
                                <p>OOPS, something went wrong but we know about it. please contact us via email or phone</p>
                            </div>
                        )}
                    </div>
                );
            }}
        </Formik>
    );
}

export default ContactForm;

Upvotes: 1

Views: 7732

Answers (1)

Pranta
Pranta

Reputation: 3695

You need to send a response back like the following

try {
  sgMail
    .send(email)
     .then(() => {
         console.log('res', res.json);
         return res.status(200).end();
     })
      .catch((error) => {
        console.log('error', error);
        return res.status(500).send(error);
     });

Upvotes: 0

Related Questions