Reputation: 1938
So I am trying to debounce some actions inside react component.
import React, {Component} from "react";
import debounce from "lodash/debounce";
...
@connect(
mapStateToProps,
{someAction}
)
class SomeClass extends Component {
constructor(props) {
...
this.debouncedAction = debounce(props.someAction, 300);// someAction works ok
}
onSomeEvent = (...args) => {
this.debouncedAction(args); // this does not work
}
}
So the modified debouncedAction
is not called. Is there a way to do that without creating extra action in mapStateToProps
?
I need to keep both because one for filtering second(debounced) for search.
Upvotes: 3
Views: 276
Reputation: 17430
It's definitely possible to debounce the event handler, which then uses the action.
class SomeClass extends Component {
// Debounce the event handler here instead
onSomeEvent = debounce((...args) => {
const { someAction } = this.props;
someAction(...args);
}, 300)
// ...
}
It also ensures that each time the event callback is executed, it uses the current prop value, so it's always up to date.
Upvotes: 3