1- import React from 'react' ;
1+ "use client" ;
2+
3+ import React , { useState } from "react" ;
4+ import { collection , addDoc , query , where , getDocs } from "firebase/firestore" ;
5+ import { db } from "../firebase/firebase" ;
6+ import { toast } from "react-toastify" ;
7+
8+ function Subscribe ( ) {
9+ const [ email , setEmail ] = useState ( "" ) ;
10+ const [ loading , setLoading ] = useState ( false ) ;
11+
12+ const handleSubscribe = async ( ) => {
13+ if ( ! email ) {
14+ toast . error ( "Please enter a valid email" ) ;
15+ return ;
16+ }
17+
18+ setLoading ( true ) ;
19+
20+ try {
21+ // Query Firestore to check if the email already exists
22+ const q = query ( collection ( db , "users" ) , where ( "email" , "==" , email ) ) ;
23+ const querySnapshot = await getDocs ( q ) ;
24+
25+ if ( ! querySnapshot . empty ) {
26+ toast . error ( "This email is already subscribed!" ) ;
27+ } else {
28+ // Add the email to the Firestore collection if it's not already there
29+ await addDoc ( collection ( db , "users" ) , { email } ) ;
30+ toast . success ( "Subscribed successfully!" ) ;
31+ setEmail ( "" ) ; // Clear input after success
32+ }
33+ } catch ( error ) {
34+ console . error ( "Error subscribing:" , error ) ;
35+ toast . error ( "Failed to subscribe. Try again!" ) ;
36+ } finally {
37+ setLoading ( false ) ;
38+ }
39+ } ;
240
3- function Subscribe ( )
4- {
541 return (
642 < div className = "relative bg-custom-blue flex flex-col items-baseline justify-center p-40 gap-4 rounded-md" >
7- < h2 className = "text-2xl text-white font-bold" > Subscribe for Updates</ h2 >
8- < div className = "relative" >
9- < div className = "relative flex" >
10- < input
11- type = "email"
12- placeholder = "Enter your email"
13- className = "p-3 pl-4 pr-32 border border-white rounded-full"
14- />
15- < button className = "absolute right-1 top-1 bg-black text-white text-custom-blue p-2 pl-6 pr-6 rounded-full" >
16- Subscribe
17- </ button >
18- </ div >
43+ < h2 className = "text-2xl text-white font-bold" > Subscribe for Updates</ h2 >
44+ < div className = "relative" >
45+ < div className = "relative flex" >
46+ < input
47+ type = "email"
48+ value = { email }
49+ onChange = { ( e ) => setEmail ( e . target . value ) }
50+ placeholder = "Enter your email"
51+ className = "p-3 pl-4 pr-32 border border-white rounded-full"
52+ disabled = { loading }
53+ />
54+ < button
55+ className = "absolute right-1 top-1 bg-black text-white text-custom-blue p-2 pl-6 pr-6 rounded-full"
56+ onClick = { handleSubscribe }
57+ disabled = { loading }
58+ >
59+ { loading ? "Subscribing..." : "Subscribe" }
60+ </ button >
1961 </ div >
20- < p className = "text-white" > Be the first to hear about our newest product updates!</ p >
62+ </ div >
63+ < p className = "text-white" >
64+ Be the first to hear about our newest product updates!
65+ </ p >
2166 </ div >
2267 ) ;
23- } ;
68+ }
2469
25- export default Subscribe ;
70+ export default Subscribe ;
0 commit comments