Untitled

 avatar
unknown
plain_text
a year ago
1.4 kB
6
Indexable
import React, {
  createContext,
  useContext,
  useState,
  ReactNode,
  useEffect,
} from 'react';
import { ToastType } from '../../components/Common/StyledToast';

interface ToastState {
  message: string;
  visible: boolean;
  type: ToastType;
}

interface ToastContextProps {
  toast: ToastState;
  showToast: (message: string, type?: ToastType) => void;
  hideToast: () => void;
}

const ToastContext = createContext<ToastContextProps | undefined>(undefined);

export const ToastProvider = ({ children }: { children: ReactNode }) => {
  const [toast, setToast] = useState<ToastState>({
    message: '',
    visible: false,
    type: 'info',
  });

  useEffect(() => {
    console.log('Toast state updated: BBB', toast);
  }, [toast]);

  const showToast = (message: string, type: ToastType = 'info') => {
    setToast({ message, visible: true, type });
    setTimeout(
      () => setToast({ message: '', visible: false, type: 'info' }),
      5000
    );
  };

  const hideToast = () => {
    setToast({ message: '', visible: false, type: 'info' });
  };

  return (
    <ToastContext.Provider value={{ toast, showToast, hideToast }}>
      {children}
    </ToastContext.Provider>
  );
};

export const useToast = (): ToastContextProps => {
  const context = useContext(ToastContext);
  if (context === undefined) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  return context;
};
Editor is loading...
Leave a Comment