Skip to content

Instantly share code, notes, and snippets.

@aibolik
Created January 12, 2020 21:12
Show Gist options
  • Select an option

  • Save aibolik/e9bc9ef12da3c15a99413643abfb05e9 to your computer and use it in GitHub Desktop.

Select an option

Save aibolik/e9bc9ef12da3c15a99413643abfb05e9 to your computer and use it in GitHub Desktop.
ToastProvider full implementation(part of post https://aibolik.github.io/blog/creating-toast-api-with-react-hooks)
const ToastContext = React.createContext(null);
let id = 1;
const ToastProvider = ({ children }) => {
const [toasts, setToasts] = useState([]);
const addToast = useCallback(content => {
setToasts(toasts => [
...toasts,
{ id: id++, content }
]);
}, [setToasts]);
const removeToast = useCallback(id => {
setToasts(toasts => toasts.filter(t => t.id !== id));
}, [setToasts]);
return (
<ToastContext.Provider value={{ addToast, removeToast }}>
<ToastContainer toasts={toasts} />
{children}
</ToastContext.Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment