How to dispatch a Redux action with a timeout?

后端 未结 12 1938
花落未央
花落未央 2020-11-22 04:14

I have an action that updates the notification state of my application. Usually, this notification will be an error or info of some sort. I need to then dispatch another act

12条回答
  •  无人共我
    2020-11-22 05:07

    Redux itself is a pretty verbose library, and for such stuff you would have to use something like Redux-thunk, which will give a dispatch function, so you will be able to dispatch closing of the notification after several seconds.

    I have created a library to address issues like verbosity and composability, and your example will look like the following:

    import { createTile, createSyncTile } from 'redux-tiles';
    import { sleep } from 'delounce';
    
    const notifications = createSyncTile({
      type: ['ui', 'notifications'],
      fn: ({ params }) => params.data,
      // to have only one tile for all notifications
      nesting: ({ type }) => [type],
    });
    
    const notificationsManager = createTile({
      type: ['ui', 'notificationManager'],
      fn: ({ params, dispatch, actions }) => {
        dispatch(actions.ui.notifications({ type: params.type, data: params.data }));
        await sleep(params.timeout || 5000);
        dispatch(actions.ui.notifications({ type: params.type, data: null }));
        return { closed: true };
      },
      nesting: ({ type }) => [type],
    });
    

    So we compose sync actions for showing notifications inside async action, which can request some info the background, or check later whether the notification was closed manually.

提交回复
热议问题