In my reactjs
redux
application I'm using redux observable epics
middleware for ajax requests to cancel some requests.
const epicRequest = $actions => {
return $actions
.ofType(MY_ACTION_TYPE)
.debounceTime(500)
.switchMap( action =>{
// Doing Ajax
})
}
My problem is I call this action when I press some buttons, I have two kinds of buttons both can call the same action, in that case if call from first action and second action is different button I don't want to debounce, I want to debounce only if the action is from same button.
To fix this you have to pass additional prop from your button call and check that prop from your epic.
Inside your component button click call, pass your button identification.
onclick = () => {
// assume arg name is 'from'
this.props.yourAction('a') // can be 'a'/'b' ...
}
In your action call, pass the value that you have got from button call.
const yourAction = (from) => {
return { type: MY_ACTION_TYPE, from }
}
In reducer switch case
case MY_ACTION_TYPE:
return {...state, from:action.from}
Finally in your epic middleware function, replce .debounceTime(600)
with .debounce()
, with this you can pass function as argument that returns Observable.timer()
. So you can check your prop here and return the debounce time.
let from = null
const epicRequest = $actions => {
return $actions
.ofType(MY_ACTION_TYPE)
//.debounceTime(500)
.debounce((action) => {
// check button type is not yet set or not previous type
const timer = !from || (from !== action.from) ? Observable.timer(0) : Observable.timer(600)
// update button type
from = (from !== action.from) ? action.from : from
// return Observable.timer()
return timer
})
.switchMap( action =>{
// Do your Ajax
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With