just started on my coding journey and as with these things, sometimes you come across a problem that you are unable to solve it despite multiple hours and attempts..
If anyone could have a look at my code and let me know where I'm going wrong - I have a sneaky suspicion that it's to do with the await fetch call, but I may be wrong.
Thanks in advance.
The component is being imported to index.jsx as, this is the code for my "Contact" component:
import React, { useRef } from 'react';
export default function Contact() {
const inputRef = useRef(null);
const subscribeUser = async (e) => {
e.preventDefault();
const res = await fetch('/api/subscribeUser', {
body: JSON.stringify({
email: inputRef.current.value,
}),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
});
};
return (
<div className="h-[150px] bg-gray-100/70 text-black/70">
<div className="flex justify-center items-center pt-2">
<h1 className="font-bold text-center text-sm md:text-2xl">
Sign up to the Newsletter...
</h1>
</div>
<div className="flex justify-center items-center w-full">
<form onSubmit={subscribeUser}>
<input
type="email"
id="email-input"
name="email"
placeholder="Your email here"
ref={inputRef}
required
autoCapitalize="off"
autoCorrect="off"
autoFill="off"
className="border min-w-[280px] py-2 px-2 text-center"
/>
<div className="flex justify-center items-center">
<button
type="submit"
value=""
name="subscribe"
className="px-4 py-1 mt-2 bg-gray-200 border border-black/40 text-gray-900 text-lg transition-colors duration-700 transform hover:bg-gray-500 hover:text-gray-100"
>
Subscribe
</button>
</div>
</form>
</div>
</div>
);
}
This is the api/subscribeUser I am trying to call:
import fetch from 'isomorphic-unfetch';
const handler = async (req, res) => {
const { email } = req.body;
console.log({ email });
if (!email) {
return res.status(200).json({ error: '*** Email is required ***' });
}
try {
const AUDIENCE_ID = process.env.MAILCHIMP_AUDIENCE_ID;
const API_KEY = process.env.MAILCHIMP_API_KEY;
const DATACENTER = process.env.MAILCHIMP_API_SERVER;
const data = {
email_address: email,
status: 'subscribed',
};
const response = await fetch(
`https://${DATACENTER}.api.mailchimp.com/3.0/lists/${AUDIENCE_ID}/members`,
{
body: JSON.stringify(data),
headers: {
Authorization: `apikey ${API_KEY}`,
'Content-Type': 'application/json',
},
method: 'POST',
}
);
if (response.status >= 400) {
return res.status(400).json({
error:
'There was an error subscribing to the newsletter, please try again with a different email address.',
});
}
return res.status(201).json({ error: '' });
} catch (error) {
return res.status(500).json({ error: error.message || error.toString() });
}
};
export default handler;