How to cancel user input in reactions using rxjs

My problem may be trivial, but so far I have not been able to find the answer.

How can I postpone (debounce) an update state in React during user input to avoid unnecessary updates?

Having <input onChange={this.onChange} .../> , how can I bind theChange event using rxjs? Should I try to make this entry visible or use the FromEventPattern parameter?

In both cases, I do not know how to associate React events with rxjs. Second question: will the user see any input changes during debounce?

+6
source share
2 answers

Decision No. 1

Theme Usage: Fiddle

 const state = new Rx.Subject() .debounceTime(1000) .scan((acc) => { return ++acc }, 0).do(::console.log) const handler = (e) => { state.next(e) } state.startWith(0).subscribe((clicks) => { ReactDOM.render(<button onClick={handler}>Clicked {clicks}</button>, document.querySelector('#app')) }) 

Decision number 2

Using rxjs fromEvent: Fiddle

 // Intial render so element exists in dom (there is probably a better pattern) ReactDOM.render( <button id='clickMe'>Click Me</button>, document.querySelector('#app')) const clicks = Rx.Observable .fromEvent(document.getElementById('clickMe'), 'click') .do(::console.log) .debounceTime(1000) .scan((acc) => { return ++acc }, 0) clicks.subscribe((clicks) => { ReactDOM.render( <button id='clickMe'>Click Me {clicks}</button>, document.querySelector('#app')) }) 

Decision No. 3

Note: very experimental, and just something that I tried to do for fun.

This is more for action-based architecture where you have actions that change your state (thread). This is a handler that is fully autonomous. It is used with the custom operator 'fromEventArgs': Fiddle (look at the console)

 const handler = (e) => { Rx.Observable .fromEventArgs(e, 'UniqueKey') .debounceTime(1000) .subscribe(x => console.log('Send an action', x)) } 
+7
source

based on omerts suggestions (especially solution # 1), here is my final code

 input: Rx.Subject<any>; constuctor(...){ this.input = new Rx.Subject(); this.input.debounce(1000).subscribe(this.processInput); } handleChange = event => { event.persist(); this.input.onNext(event); }; processInput = x => { // invoke redux/flux action to update the state } render(){ ... <input onChange={this.handleChange} ... /> ... } 
+6
source

All Articles