简体   繁体   中英

Apply a throttled middleware in redux

I am creating a small middleware for redux. Since my electron application connects to another database and updates it's state (so that I may see the state of this application on my main application). Here is my basic code:

const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];

export remoteMiddleware => store => next => action => {
  const db = MongoClient.connect(process.env.MONGO_URL);
  try {
    if (!BLACKLIST.includes(action.type)) {
      const state = store.getState();
      db.collection('state').update(
        { _id: process.env.APP_ID },
        { $set: { state } }
      )
    }
  } finally {
    db.close();
  }
}

However, I am having a bit of a problem where this is firing TOO often, when it doesn't always need to fire immediately. I would prefer if it fired every n iterations, or perhaps no more than x ms.

Is there a way to throttle a redux middleware so that it will only fire every n times, or such that it will only run every x number of ms?

How about simply

const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];
var lastActionTime = 0;

export remoteMiddleware => store => next => action => {
  let now = Date.now();
  try {
    if (!BLACKLIST.includes(action.type) && now - lastActionTime > 100)
    ...
  } finally() {
    lastActionTime = now;
    db.close();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM