timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.79k stars 331 forks source link

toast in async event handler #109

Closed andrekat closed 3 years ago

andrekat commented 3 years ago

Hey!

I am getting a really weird error when sending a toast in an async event handler (onClick).

Error: Objects are not valid as a React child (found: object with keys {code, message, stack}). If you meant to render a collection of children, use an array instead.
    in div (created by a)
    in a
    in div (created by ForwardRef(a))
    in ForwardRef(a)
    in Unknown (created by Toaster)
    in div (created by Toaster)
    in div (created by Toaster)
    in Toaster (at App.tsx:56)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.tsx:34)
  162 | export const dispatch = (action: Action) => {
  163 |   memoryState = reducer(memoryState, action);
  164 |   listeners.forEach((listener) => {
> 165 |     listener(memoryState);
  166 |   });
  167 | };
  168 | 
View compiled
dispatch
D:/src/core/store.ts:164
  161 | 
  162 | export const dispatch = (action: Action) => {
  163 |   memoryState = reducer(memoryState, action);
> 164 |   listeners.forEach((listener) => {
  165 |     listener(memoryState);
  166 |   });
  167 | };
View compiled
Function.error
D:/src/core/toast.ts:40
  37 |   options
  38 | ) => {
  39 |   const toast = createToast(message, type, options);
> 40 |   dispatch({ type: ActionType.UPSERT_TOAST, toast });
  41 |   return toast.id;
  42 | };
  43 | 
View compiled
onBuy
D:/src/pages/Apps/PowerScratcher/components/Buy.tsx:177
  174 |     }
  175 | } catch (error) {
  176 |     console.log(error)
> 177 |     toast.error(error)
      | ^  178 | } finally {
  179 |     setShowBuyLoading(false)
  180 | }
timolins commented 3 years ago

It looks like you are trying to render an error object, which is not a valid React child. You would need to convert it to a string or just use toast.error(error.message).