Im making a website for a customer. It is a store for kids toys. After the customer pays through stripe its redirected to success page. On success page Im sending an email using email js inside useEffect. In that email I place links for each item ordered so that customer can click and give review to specific item. There are two issues im facing. 1. I only want that page to be accessible after the payment so the user cant type the url and go to success page without payment. 2. when user is on success page, every time he/she refreshes the page, an email will be sent. I want that email to be sent only once. Is there a way to do this. Im attaching success page code below.
import React, { useState, useEffect, useRef } from "react";
import congrats from "../assets/Congrats.png";
import { Link } from "react-router-dom";
import emailjs from "@emailjs/browser";
import { useParams } from "react-router-dom";
import axios from "axios";
const SuccessPage = () => {
const [cartIds, setCartIds] = useState([]);
const [linkString, setLinkString] = useState("");
const [customerEmail, setCustomerEmail] = useState(null);
const [customerName, setCustomerName] = useState(null);
const { id } = useParams();
const dataRef = useRef();
useEffect(() => {
sessionDetails();
}, []);
useEffect(() => {
getCartItems();
generateLinkStrings();
dataRef.data = {
name: customerName,
email: customerEmail,
link: linkString,
};
if (dataRef.data.name && dataRef.data.email) {
sendEmail();
}
}, [customerEmail, customerName]);
const getCartItems = () => {
const cart = localStorage.getItem("cart");
const cartIds = JSON.parse(cart).map((item) => {
return { id: item.id, name: item.name };
});
setCartIds(cartIds);
};
const generateLinkStrings = () => {
let tempString = "";
cartIds.map((item) => {
tempString += `${item.name} : ${window.location.origin}/review/${item.id}<br>`;
return null;
});
setLinkString(tempString);
};
const sessionDetails = async () => {
const url = "/.netlify/functions/retrieve-session";
const { data } = await axios.post(url, id);
setCustomerEmail(data.session.customer_details.email);
setCustomerName(data.session.customer_details.name);
};
const sendEmail = () => {
emailjs
.send(
"my sevice",
"my template",
dataRef.data,
"my key"
)
.then(
function (response) {
console.log("SUCCESS!", response.status, response.text);
},
function (error) {
console.log("FAILED...", error);
}
);
};
return (
<section className="success-page">
<div className="success-detail-container">
<div className="success-details">
<img src={congrats} alt="" />
<h1>Your order is complete!</h1>
<p>You will be receiving a confirmation email with order details.</p>
<button className="success-btn" type="button">
<Link to="/digital">Explore free digital downloads</Link>
</button>
</div>
</div>
</section>
);
};
export default SuccessPage;