-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathuse-newsletter-subscription.ts
81 lines (71 loc) · 1.98 KB
/
use-newsletter-subscription.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"use client";
import { useState } from "react";
const url = process.env.NEXT_PUBLIC_SUPABASE_URL + "/rest/v1/prelaunch_subscribers";
const apiKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
export default function useNewsletterSubscription() {
const initialState = {
email: "",
isLoading: false,
error: "",
success: false,
};
const [state, setState] = useState(initialState);
const setEmail = (email: string) => {
setState({ ...state, email });
};
const addSubscriber = async () => {
// Validate email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(state.email)) {
setState({
...state,
error: "Please enter a valid email address.",
});
return;
}
setState({ ...state, isLoading: true });
const data = { email: state.email };
try {
const response = await fetch(url, {
method: "POST",
// @ts-expect-error - Types for custom headers are not defined in fetch types
headers: {
apikey: apiKey,
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json",
Prefer: "return=minimal",
},
body: JSON.stringify(data),
});
if (response.status >= 200 && response.status < 300) {
// Email added successfully
setState({
...initialState,
isLoading: false,
success: true,
});
return;
}
if (response.status === 409) {
// Already subscribed
setState({
...initialState,
error: "You are already subscribed!",
});
return;
}
// Other errors
const errorData = await response.json();
setState({
...initialState,
error: errorData.message || "An unknown error occurred",
});
} catch (error) {
setState({
...initialState,
error: (error as Error).message,
});
}
};
return { ...state, addSubscriber, setEmail };
}