Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

debounce? #8

Open
amasad opened this issue Feb 15, 2016 · 2 comments
Open

debounce? #8

amasad opened this issue Feb 15, 2016 · 2 comments

Comments

@amasad
Copy link

amasad commented Feb 15, 2016

What's the best way to debounce server requests?
I have an editable text area that I want to do auto save on. The textareas' value is handled by redux but I don't want to overwhelm the server with updates on every keystroke. Any ideas?

@ForbesLindesay
Copy link
Owner

That's an interesting problem, and not one I've had to tackle yet personally. I think one option would be to always make your transaction ID something like the ID of the thing you are updating, then always fire a REVERT action before firing your begin transaction action. e.g.

import {BEGIN, COMMIT, REVERT} from 'redux-optimist';
import request from 'then-request';

const inProgress = {};
export default function (store) {
  return next => action => {
    if (action.type !== 'SET_VALUE') {
      return next(action);
    }
    const key = action.key;
    if (key in inProgress) {
      clearTimeout(inProgress[key]);
      next({
        type: 'PREPARE_DEBOUNCED_SET',
        optimist: {type: REVERT, id: key}
      });
    }
    next({
      ...action,
      optimist: {type: BEGIN, id: key}
    });
    inProgress[key] = setTimeout(() => {
      delete inProgress[key];
      request('POST', '/add_todo', {text: action.text}).getBody().done(
        res => next({
          ...action,
          type: 'SET_VALUE_COMPLETE',
          response: res,
          optimist: {type: COMMIT, id: key}
        }),
        err => next({
          ...action,
          type: 'SET_VALUE_FAILED',
          error: err,
          optimist: {type: REVERT, id: key}
        })
      );
    }, 1000);
  };
};

I haven't tested that, so I don't know for sure whether it works properly. It occurs to me that maybe we shouldn't have a special BEGIN type, and should just automatically BEGIN when you fire the first action with a given transactionID. That would allow you to remove the bit where you fire an action to revert the in-progress transaction.

@amasad
Copy link
Author

amasad commented Feb 28, 2016

Very briefly tried to implement this and it proved a bit tricky. I ended up keeping component local state and then debouncing the action dispatch at the component level. I may come back to this in the future though since it's nice to not have local state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants