error.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use client";
  2. import { useEffect } from 'react'
  3. import { useRouter } from 'next/navigation';
  4. import { signOut } from "next-auth/react";
  5. import { useAppDispatch } from "@/store/hooks";
  6. import { clearCart } from "@/store/slices/cart-slice";
  7. //https://nextjs.org/docs/app/api-reference/file-conventions/error
  8. export default function Error({
  9. error,
  10. reset
  11. }: {
  12. reset: () => void;
  13. error: Error & { digest?: string };
  14. }) {
  15. const router = useRouter();
  16. const dispatch = useAppDispatch();
  17. let msg = "There was an issue with our storefront. This could be a temporary issue, please try your action again.";
  18. if(error.name === 'UnauthorizedError') {
  19. msg = "Authorization Bearer token is required. Will redirect to Login page.";
  20. }
  21. const clickHandler = () => {
  22. if(error.name === 'UnauthorizedError') {
  23. router.push('/customer/login')
  24. } else {
  25. reset();
  26. }
  27. };
  28. useEffect(() => {
  29. if (error.name === "UnauthorizedError") {
  30. signOut({
  31. callbackUrl:"/customer/login",
  32. redirect: false,
  33. }).then(() => {
  34. dispatch(clearCart());
  35. setTimeout(() => {
  36. router.push("/customer/login");
  37. router.refresh();
  38. }, 100);
  39. });
  40. }
  41. // Log the error to an error reporting service
  42. console.error(error)
  43. }, [error])
  44. return (
  45. <div className="mx-auto my-4 flex max-w-xl flex-col rounded-lg border border-neutral-200 bg-white p-8 md:p-12 dark:border-neutral-800 dark:bg-black">
  46. <h2 className="text-xl font-bold">Oh no!</h2>
  47. <p className="my-2">
  48. {msg}
  49. </p>
  50. <button
  51. className="mx-auto mt-4 flex w-full items-center justify-center rounded-full bg-blue-600 p-4 tracking-wide text-white hover:opacity-90"
  52. onClick={clickHandler}
  53. >
  54. {error.name === 'UnauthorizedError' ? "To Login" : "Try Again"}
  55. </button>
  56. </div>
  57. );
  58. }