Listening for a redux action

∥☆過路亽.° 提交于 2019-12-05 08:31:23

If I'm understanding correctly, it sounds like the REFRESH_DATA action is mainly a side effect, meaning that action is only dispatched as a result of another action. If that is the case then I'd say redux saga would be a good choice because it can sit in the background and "listen" for actions and then trigger other actions. But, you may be able to get pretty far with a custom middleware.

With custom middleware you can intercept actions as they are dispatched before they hit the reducers. If you're going to have a bunch of actions all related to updating a table and refreshing data, it might make sense to create a common action shape for all of those kinds of actions so that you're middleware can listen for it and dispatch special side-effect actions.

A simple implementation might look something like this:

middleware/table.js

import fetchData from '../somewhere';
import { DATA_REFRESHED } from '../actions';

// Make a unique identifier that you're actions can send so you're
// middleware can intercept it
export const UPDATE_TABLE = Symbol('UPDATE_TABLE');

export default store => next => action => {
  const tableUpdate = action[UPDATE_TABLE];

  // If the action doesn't have the symbol identifier, just move on
  if (typeof tableUpdate === 'undefined') {
    return next(action);
  }

  // At this point, you know that the action that's been dispatched 
  // is one that involves updating the table, so you can do a fetch
  // for data

  // Get whatever data you need to fetch 
  const { id, type, data } = tableUpdate;

  // Dispatch the actual type of action to the store
  next({ type, data });

  // Go and fetch the data as a side-effect
  return fetchData(id)
    .then(response => next({ type: DATA_REFRESHED, data: response }));
}

actions.js

import { UPDATE_TABLE } from '../middleware/table.js';

// An action creator to dispatch the special table update action
// This is a simple example, but you'd probably want to be consistent
// about how the table update actions are shaped.  The middleware 
// should be able to pick out all of the data it needs to fetch data
// from whatever is sent with the action
function updateTable(action) {
    return {
        [UPDATE_TABLE]: action
    };
}

export function currentPageUpdated(value) {
    return updateTable({
        type: CURRENT_PAGE_UPDATE,
        value
    });
}

I took a lot this from the real world example: https://github.com/rackt/redux/blob/master/examples/real-world/middleware/api.js.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!