From 70796634ef7f6e2cf5a8453f70bc2f5ba9d10bdd Mon Sep 17 00:00:00 2001 From: Ryan Florence Date: Mon, 10 Jan 2022 16:11:06 -0700 Subject: [PATCH] protip: add some UI feedback to the add to cart button --- app/components/product-details.tsx | 46 ++++++++++++++++++++++++++---- app/translations.server.tsx | 8 ++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/app/components/product-details.tsx b/app/components/product-details.tsx index 68033d9..7441f56 100644 --- a/app/components/product-details.tsx +++ b/app/components/product-details.tsx @@ -1,6 +1,6 @@ -import { useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import type { MouseEventHandler } from "react"; -import { Form, useLocation, useSearchParams } from "remix"; +import { Form, useLocation, useSearchParams, useTransition } from "remix"; import cn from "classnames"; import type { FullProduct } from "~/models/ecommerce-provider.server"; @@ -12,7 +12,9 @@ export function ProductDetails({ translations, }: { product: FullProduct; - translations: PickTranslations<"Add to cart" | "Sold out">; + translations: PickTranslations< + "Add to cart" | "Sold out" | "Added!" | "Adding" + >; }) { let location = useLocation(); let [searchParams] = useSearchParams(); @@ -82,6 +84,11 @@ export function ProductDetails({ ) : null}
+ - {translations["Add to cart"]} + @@ -112,6 +122,32 @@ export function ProductDetails({ ); } +function SubmissionSequenceText({ + strings, + action, +}: { + strings: String[]; + action: string; +}) { + let transition = useTransition(); + let [text, setText] = useState(strings[0]); + + useEffect(() => { + if (transition.submission?.formData.get("_action") === action) { + if (transition.state === "submitting") { + setText(strings[1]); + } else if (transition.state === "loading") { + setText(strings[2]); + } + } else { + let id = setTimeout(() => setText(strings[0]), 1000); + return () => clearTimeout(id); + } + }, [transition]); + + return {text}; +} + function ImageSlider({ images }: { images: string[] }) { let sliderListRef = useRef(null); let scrollToImage: MouseEventHandler = (event) => { diff --git a/app/translations.server.tsx b/app/translations.server.tsx index a3ea1c9..65e0757 100644 --- a/app/translations.server.tsx +++ b/app/translations.server.tsx @@ -100,6 +100,14 @@ let translations = { en: "Add to cart", es: "Añadir al carrito", }, + Adding: { + en: "Adding...", + es: "Agregando...", + }, + "Added!": { + en: "Added!", + es: "¡Adicional!", + }, "Sold out": { en: "Sold out", es: "No disponible",