Commit 0f46e9c8 by HoMeTown

feat: toast封装

parent 6c08913b
......@@ -46,6 +46,7 @@
"clsx": "^2.1.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hot-toast": "^2.4.1",
"react-router-dom": "^6.26.0",
"react-virtuoso": "^4.9.0",
"tailwind-merge": "^2.4.0"
......
......@@ -4,9 +4,11 @@ import { BrowserRouter as Router } from 'react-router-dom'
import { MainLayout } from './layouts'
import { AppRoutes } from './routes/AppRoutes'
import { AuthProvider } from './auth/AuthContext'
import ToastWrapper from './components/ToastWrapper/ToastWrapper'
const App: React.FC = () => {
return (
<ToastWrapper>
<AuthProvider>
<Router>
<MainLayout>
......@@ -14,6 +16,7 @@ const App: React.FC = () => {
</MainLayout>
</Router>
</AuthProvider>
</ToastWrapper>
)
}
......
......@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
import React, { createContext, useContext, useState } from 'react'
import { useLocalStorageState } from 'ahooks'
import { fetchLoginByUid } from '@/api/common'
import useToast from '@/hooks/useToast'
interface AuthContextType {
isLoggedIn: boolean
......@@ -20,6 +21,7 @@ interface AuthProviderProps {
}
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const showToast = useToast()
const [token, setToken] = useLocalStorageState<string | undefined>(
'__TOKEN__',
{
......@@ -36,7 +38,10 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
setToken(res.data.token)
setIsLoggedIn(true)
setShowLoginModal(false)
showToast('登录成功!', 'success')
return
}
showToast('登录失败', 'error')
}
const logout = () => {
......
// ToastWrapper.tsx
import type { ReactNode } from 'react'
import React from 'react'
import { Toaster } from 'react-hot-toast'
interface ToastWrapperProps {
children: ReactNode
}
const ToastWrapper: React.FC<ToastWrapperProps> = ({ children }) => {
return (
<>
{children}
<Toaster />
</>
)
}
export default ToastWrapper
import type { Toast } from 'react-hot-toast'
import { toast } from 'react-hot-toast'
type ToastType = 'success' | 'error' | 'default'
interface ToastOptions {
duration?: number
position?: Toast['position']
icon?: string
}
function useToast() {
const showToast = (message: string, type: ToastType = 'default', options?: ToastOptions): string => {
const { duration, position, icon } = options || {}
switch (type) {
case 'success':
return toast.success(message, { duration, position, icon })
case 'error':
return toast.error(message, { duration, position, icon })
default:
return toast(message, { duration, position, icon })
}
}
return showToast
}
export default useToast
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment