Skip to content

useOptimistic is redundant when sonner is in use #1

@xc1427

Description

@xc1427

This is not a bug report, but rather an observation for those who might encounter similar confusion.

sonner manages its own state regarding dismissal, and the dismiss action takes immediate visual effect, regardless of whether useOptimistic is used.

In essence, a simplified client-toasts.tsx will function seamlessly:

"use client";

import { useEffect, useState } from "react";
import { Toaster as SonnerToaster, toast as sonnerToast } from "sonner";

type Toast = {
  id: string;
  message: string;
  dismiss: () => Promise<void>;
};

export function ClientToasts({ toasts }: { toasts: Toast[] }) {
  const localToasts = toasts.map((toast) => ({
    ...toast,
    dismiss: async () => {
      await toast.dismiss();
      console.log('debug', 'dismissal complete');
    },
  }));

  const [sentToSonner, setSentToSonner] = useState<string[]>([]);

  useEffect(() => {
    localToasts
      .filter((toast) => !sentToSonner.includes(toast.id))
      .forEach((toast) => {
        setSentToSonner((prev) => [...prev, toast.id]);
        sonnerToast(toast.message, {
          id: toast.id,
          onDismiss: () => toast.dismiss(),
          // onAutoClose: () => toast.dismiss(),
          closeButton: true,
          position: "top-right",
        });
      });
  }, [toasts, sentToSonner]);

  return <SonnerToaster />;
}


Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions