11import { useState } from "react" ;
22import PropTypes from "prop-types" ;
3+ import { useAuth } from "../store/auth" ;
4+ import { toast } from "react-toastify" ;
35
46const EMAIL_REGEX = / ^ [ ^ \s @ ] + @ [ ^ \s @ ] + \. [ ^ \s @ ] + $ / ;
57
68function NewsletterSubscribeInput ( { isDark } ) {
9+ const { API } = useAuth ( ) ;
710 const [ email , setEmail ] = useState ( "" ) ;
8- const [ status , setStatus ] = useState ( { type : "idle" , message : "" } ) ;
911 const [ loading , setLoading ] = useState ( false ) ;
1012
1113 const handleSubscribe = async ( ) => {
1214 if ( ! EMAIL_REGEX . test ( email ) ) {
13- setStatus ( { type : "error" , message : " Please enter a valid email." } ) ;
15+ toast . error ( " Please enter a valid email.") ;
1416 return ;
1517 }
1618 try {
1719 setLoading ( true ) ;
18- setStatus ( { type : "idle" , message : "" } ) ;
1920 const res = await fetch (
20- "http://localhost:5050/ api/newsletter/subscribe" ,
21+ ` ${ API } / api/newsletter/subscribe` ,
2122 {
2223 method : "POST" ,
2324 headers : { "Content-Type" : "application/json" } ,
@@ -28,13 +29,13 @@ function NewsletterSubscribeInput({ isDark }) {
2829 if ( ! res . ok || data ?. success === false ) {
2930 throw new Error ( data ?. message || "Subscription failed" ) ;
3031 }
31- setStatus ( { type : "success" , message : data ?. message || "Subscribed!" } ) ;
32+ if ( data ?. message == "Already subscribed" )
33+ toast . info ( data ?. message || "Subscribed!" )
34+ else
35+ toast . success ( data ?. message || "Subscribed!" )
3236 setEmail ( "" ) ;
3337 } catch ( err ) {
34- setStatus ( {
35- type : "error" ,
36- message : err . message || "Something went wrong" ,
37- } ) ;
38+ toast . error ( err ?. message || "Something went wrong" ) ;
3839 } finally {
3940 setLoading ( false ) ;
4041 }
@@ -59,21 +60,12 @@ function NewsletterSubscribeInput({ isDark }) {
5960 < button
6061 onClick = { handleSubscribe }
6162 disabled = { loading }
62- className = { `bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors my-3 mx-1 shadow-md ${
63+ className = { `bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg transition-colors shadow-md ${
6364 loading ? "opacity-70 cursor-not-allowed" : ""
6465 } `}
6566 >
6667 { loading ? "Subscribing..." : "Subscribe" }
6768 </ button >
68- { status . message && (
69- < div
70- className = { `text-sm my-auto ${
71- status . type === "error" ? "text-red-500" : "text-green-500"
72- } `}
73- >
74- { status . message }
75- </ div >
76- ) }
7769 </ div >
7870 ) ;
7971}
0 commit comments