Created
April 14, 2022 08:29
-
-
Save ziedHamdi/4687fe8ad0a8576ded25ebe9a1563639 to your computer and use it in GitHub Desktop.
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
/** | |
* inspired from https://www.yld.io/blog/global-notifications-with-reacts-context-api/ | |
*/ | |
import React, { useState, useCallback } from 'react'; | |
export const ToastContext = React.createContext({ | |
toasts: null, | |
addToast: () => {}, | |
removeToast: () => {}, | |
}); | |
export default function ToastContextProvider({ children }) { | |
const [toasts, setToasts] = useState([]); | |
function id(toast) { | |
return toast.__id | |
} | |
const addToast = (toast) => { | |
toast.__id ??= new Date() | |
setToasts( (toasts)=>[...toasts, toast]); | |
return id(toast) | |
} | |
const removeToast = (toast) => { | |
setToasts( (toastList) => { | |
return toastList.filter((current) => id(current) !== id(toast)) | |
}) | |
} | |
const contextValue = { | |
toasts: toasts, | |
addToast: useCallback((error) => addToast(error), []), | |
removeToast: useCallback((error) => removeToast(error), []) | |
}; | |
return ( | |
<ToastContext.Provider value={contextValue}> | |
{children} | |
</ToastContext.Provider> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment