[英]What is the correct way to do an async action using redux observable and firebase?
so I have this epic所以我有这部史诗
export const listenToCountryVisitsEpic = (action$, store) => {
return action$.pipe(
ofType('UPDATE_TRIP_DETAILS'),
mergeMap((action) => {
const userId = store.value.user.id
const { country, newDetails } = action
const { people, places } = details
const scheme = {
people,
places,
}
firebase.database().ref(`users/${userId}/path`).update(scheme)
return mergeMap((response) => {
const payload = { ...JSON.parse(response.request.body), currentDetails: action.currentDetails }
return [updatedCountrySuccess(payload)]
})
}),
)
}
what I want to do is make the request to firebase and then if successful update redux which in turn will update react.我想要做的是向 firebase 提出请求,然后如果成功更新 redux ,这反过来将更新反应。 if not successful then catch it如果不成功,则抓住它
this is correctly posting to firebase but I need to catch errors correctly.这是正确发布到 firebase 但我需要正确捕获错误。 I don't want to fire this: updatedCountrySuccess
until I know it's a success or failure in firebase我不想触发这个: updatedCountrySuccess
直到我知道它在 firebase 中是成功还是失败
can I use async/await for this?我可以为此使用 async/await 吗?
You can use from()
to turn Promise into Observable and then catchError
to replace the error with whatever you want.您可以使用from()
将 Promise 转换为 Observable ,然后catchError
将错误替换为您想要的任何内容。
import { from } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
return action$.pipe(
ofType('UPDATE_TRIP_DETAILS'),
mergeMap((action) => {
const userId = store.value.user.id
const { country, newDetails } = action
const { people, places } = details
const scheme = {
people,
places,
}
return from(firebase.database().ref(`users/${userId}/path`).update(scheme))
.pipe(
// `mergeMap` will handle only `next` notifications
mergeMap((response) => {
const payload = ...
return [updatedCountrySuccess(payload)]
}),
catchError(error => of(errorAction)),
);
}),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.