Pressidian
花园入口
笔记
项目
关于
实验室
GitHub
花园入口
笔记
项目
关于
实验室
GitHub

KNOWLEDGE PATHS

笔记库
当前位置
笔记库/前端/项目笔记/代达罗斯/模式/Zustand

createToastStore

1 分钟阅读 · Note

目录树 578 篇

              • createToastStore
              • ToastStoreProvider
              • Zustand 5.x API
            • 表单最佳实践指南
            • 双层级导航结构
            • 以schema为中心的
            • 异步三态切换
            • 用neverthrow进行错误处理
            • Anatomy
            • cn
            • LoadingState&useList的组合
            • procedure中的service位置
            • scrollbar-gutter
            • TailwindCSS
            • TanStack Router 路由模式
            • useDebounce
            • useForm
            • void
          • 项目待做
          • 性能优化
          • UI设计
      • 前端技术栈
    • 笔记目录
    • CLAUDE.md
    • Vue 组件与 Render 函数

关联笔记 6

↗ToastStoreProvider同一路径↗Zustand 5.x API同一路径↗表单最佳实践指南共同主题↗双层级导航结构共同主题↗以schema为中心的共同主题↗异步三态切换共同主题
  • createToastStore

createToastStore


源码

import { createStore, type StoreApi, type StateCreator } from "zustand";
import { createContext, useContext } from "react";

export interface ToastMessage {
  id: string;
  type: "success" | "error";
  title: string;
  description?: string;
  duration?: number;
}

export interface ToastSlice {
  toasts: ToastMessage[];
  addToast: (toast: Omit<ToastMessage, "id"> & { id?: string }) => void;
  removeToast: (id: string) => void;
}

export type ToastStore = StoreApi<ToastSlice>;

export type ToastStoreSlice<T = ToastSlice> = StateCreator<ToastSlice, [], [], T>;

export const createToastSlice = (set: Parameters<ToastStoreSlice>[0]): ToastSlice => ({
  toasts: [],
  addToast: (toast) => {
    const id = toast.id ?? Math.random().toString(36).slice(2, 9);
    set((state) => ({
      toasts: [...state.toasts.filter((t) => t.id !== id), { ...toast, id }],
    }));
  },
  removeToast: (id) => {
    set((state) => ({
      toasts: state.toasts.filter((toast) => toast.id !== id),
    }));
  },
});

export const createToastStore = (): ToastStore =>
  createStore<ToastSlice>()((set) => createToastSlice(set));

export const ToastStoreContext = createContext<ToastStore | null>(null);

export const useToastStore = (): ToastStore => {
  const context = useContext(ToastStoreContext);
  if (!context) {
    throw new Error("useToastStore must be used within ToastStoreProvider");
  }

  return context;
};