-
Notifications
You must be signed in to change notification settings - Fork 988
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: move NotificationProvider into Notifications folder
- Loading branch information
1 parent
389bf0b
commit 9499aa1
Showing
2 changed files
with
64 additions
and
113 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
64 changes: 64 additions & 0 deletions
64
frontend/components/context/Notifications/NotificationProvider.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { createContext, ReactNode, useContext, useState } from "react"; | ||
|
||
import Notifications from "./Notifications"; | ||
|
||
type NotificationType = "success" | "error"; | ||
|
||
export type Notification = { | ||
text: string; | ||
type: NotificationType; | ||
}; | ||
|
||
type NotificationContextState = { | ||
createNotification: ({ text, type }: Notification) => void; | ||
}; | ||
|
||
const NotificationContext = createContext<NotificationContextState>({ | ||
createNotification: () => console.log("createNotification not set!"), | ||
}); | ||
|
||
export const useNotificationContext = () => useContext(NotificationContext); | ||
|
||
interface NotificationProviderProps { | ||
children: ReactNode; | ||
} | ||
|
||
const NotificationProvider = ({ children }: NotificationProviderProps) => { | ||
const [notifications, setNotifications] = useState<Notification[]>([]); | ||
|
||
const clearNotification = (text?: string) => { | ||
if (text) { | ||
return setNotifications((state) => | ||
state.filter((notif) => notif.text !== text) | ||
); | ||
} | ||
|
||
return setNotifications([]); | ||
}; | ||
|
||
const createNotification = ({ text, type = "success" }: Notification) => { | ||
const doesNotifExist = notifications.some((notif) => notif.text === text); | ||
|
||
if (doesNotifExist) { | ||
return; | ||
} | ||
|
||
return setNotifications((state) => [...state, { text, type }]); | ||
}; | ||
|
||
return ( | ||
<NotificationContext.Provider | ||
value={{ | ||
createNotification, | ||
}} | ||
> | ||
<Notifications | ||
notifications={notifications} | ||
clearNotification={clearNotification} | ||
/> | ||
{children} | ||
</NotificationContext.Provider> | ||
); | ||
}; | ||
|
||
export default NotificationProvider; |