0

I'm currently working on a notification component using toast-react and useReducer hook. I'm thinking to trigger the notification in the reducer method. Will there an issue/side effects with this approach?

First time to use react's userReducer() hook and wondering if there are best practices or at least what shouldn't be in the reducer. Almost all the tutorials i've read only manipulates the state in the reducer, so now i'm wondering if it's a good idea to inject non-state manipulation stuff in it.

const renderToast = (props) => { /* logic to switch toast type...*/}    

export function toastReducer(
      state: ToastState,
      action: ToastActions,
    ) {
      switch (action.type) {
        case ToastActionType.DisplayToast:
          renderToast(action.payload); // <- is there a better way of doing this? is this the right place to inject this?
          return {
            ...state,
            ...action.payload,
          };
       
        default:
          return state;
      }
    }

I would appreciate if you can share your thoughts on this. TIA!

Update

Thinking to make a component wrapper that "observes" the state value.

const ToastComponent = () => {
  const  displayToast = (toastState) => {
    switch(toastState.toastType){
      case toastType.Error:
        toastError(toastState.message, 1000)
        break;
      case toastType.Success:
        toastError(toastState.message, 1000)
        break;
      default:
        break;
    }
  }
  
  useEffect(()=>{
    displayToast()
  }, [displayToast]);

  return (
    <ToastProvider value={toastState}>
      <ToastContainer />
    </ToastProvider>
  )
}
Wreeecks
  • 2,186
  • 1
  • 33
  • 53
  • You would use the `useReducer` hook to store the state, which could look something like `{ open: true, title: 'My Toast', message: 'The message of the toast'}`. Then you use that state to render the Toast component. You would dispatch actions to open a new toast or to expire the current toast. – Linda Paiste Oct 07 '22 at 03:43
  • @LindaPaiste thanks for your reply. Yes, i get what. you mean. I actually injected the toast trigger in dispatch. please see the code above. thanks! – Wreeecks Oct 07 '22 at 04:22
  • Yeah I would not do it there. A reducer should be free of side-effects. – Linda Paiste Oct 07 '22 at 04:23
  • @LindaPaiste how will you refactor this? should i make a toast component/wrapper that observes the state? – Wreeecks Oct 07 '22 at 04:38

0 Answers0