I'm trying to implement the following toast manager to my react typescript application
https://codesandbox.io/s/react-toasts-melne?from-embed=&file=/src/contexts/ToastContext.js
I've created a file called toast-context.tsx
import React, { useCallback, useEffect, useState, createContext } from 'react';
const ToastContext = createContext(null);
export default ToastContext;
export function ToastContextProvider({ children }) {
const [toasts, setToasts] = useState([]);
useEffect(() => {
if (toasts.length > 0) {
const timer = setTimeout(() => setToasts((toasts) => toasts.slice(1)), 6000);
return () => clearTimeout(timer);
}
}, [toasts]);
const addToast = useCallback(
function (toast) {
setToasts((toasts) => [...toasts, toast]);
},
[setToasts],
);
return (
<ToastContext.Provider value={addToast}>
{children}
<div style={{ position: 'fixed', bottom: '1 rem', left: '1 rem' }}>
{toasts.map((toast) => (
<div style={{ background: 'green', color: 'white' }} key={toast}>
{toast}
</div>
))}
</div>
</ToastContext.Provider>
);
}
And a hook as useToast
import { useContext } from 'react';
import ToastContext from '../contexts/toast-context';
export default function useToast() {
return useContext(ToastContext);
}
And in my _app.tsx (This is nextjs)
return (
<>
<div className="app">
<ToastContextProvider>
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
</ToastContextProvider>
</div>
</>
);
};
But when i try to use the solution, it says Uncaught TypeError: addToast is not a function
export const ToastTest = () => {
const [text, setText] = useState('');
const addToast = useToast();
function handleTextChange(event) {
setText(event.target.value);
}
function handleClick() {
addToast(text);
}
return (
<div>
<h1>Hello Toasts!</h1>
<div>
<input value={text} onChange={handleTextChange} />
</div>
<button onClick={handleClick}>Show toast</button>
</div>
);
};
I followed everything that was in the example. In the example it works but not sure why it does not work in my code.Can someone please point out the issue?
When i click on the ''Show toast' button this is the error i'm getting
