I am facing an issue where I'm dispatching an action twice in my useEffect
with different payloads. Both actions are correctly dispatched but only the second one executes my epic function.
Here is my useEffect
useEffect (() => {
dispatch (actions.getDashboardData ({
viewKey: DASHBOARD_KINDS.PUBLISHER,
widgetKey: DASHBOARD_WIDGETS.KEY_METRICS,
isOldData: false,
data: {
metrics: query.metrics,
dimensions: query.dimensions,
interval: {
begin: "2023-05-27T00:00:00",
end: "2023-05-31T00:00:00"
}
}
}))
dispatch (actions.getDashboardData ({
viewKey: DASHBOARD_KINDS.PUBLISHER,
widgetKey: DASHBOARD_WIDGETS.KEY_METRICS,
isOldData: true,
data: {
metrics: query.metrics,
dimensions: query.dimensions,
interval: {
begin: "2023-05-23T00:00:00",
end: "2023-05-27T23:00:00"
}
}
}))
}, [])
Below is my Epic function
const getDashboardDataEpic = (action$, state$) => action$
.pipe (
ofType (types.GET_DASHBOARD_DATA),
switchMap (({ payload }) => {
const { api, session } = state$.value
const { data, widgetKey, viewKey, isOldData } = payload
console.log ("Processing...", payload)
const httpPayload = {/**Payload Data**/}
return pipe ([
setMethod (HTTP_METHOD.POST),
setPath (API_ENDPOINTS.DASHBOARD_SEARCH),
send (httpPayload)
]) (api)
.pipe (
map ((http) => {
return actions.getDashboardDataSuccess ({
data: http.response,
//..remaining data
})
}),
catchError (http => {
// Error handling
}
)
)
})
)
export default combineEpics (
getDashboardDataEpic
)
As mentioned earlier, both are correctly dispatched but at the end only the second dispatch executes the epic function
Thanks
switchMap()
enforces that only one inner observable is subscribed to at any given time. So when you dispatch the second action before the inner observable http request has finished it unsubscribes from that first inner observable. If you instead want them to run concurrently you can use mergeMap()
. If you want to them run sequentially, use concatMap()
.