如何使用 redux observable 向 firebase `once` 发出异步请求?
How do you make an async request to firebase `once` using redux observable?
这是我的史诗,但它不起作用。
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap(async (action) => {
const readData = firebaseApp.database().ref(`users/${id}`)
const myData = await readData.once('value').then((snapshot) => {
const data = snapshot.val()
// console.log(data) this works correctly
return data
})
return [fetchDataFulfilled(myData)]
}),
catchError((e) =>
of({
type: 'FAILED_TO_FETCH_DATA',
e,
}),
),
)
当我在 await 中记录数据时,它就在那里。但出于某种原因我无法将其传递给操作来实现它
错误是说:Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
但这是中间件?
所以我的主要问题是,如何等待 firebase 完成,然后将数据正确发送到我的史诗?
我认为你必须使用 rxjs
from operator
将 Promise 转换为 observable
import { from } from 'rxjs';
const fetchUserFulfilled = payload => ({ type: `FETCH_USER_FULFILLED`, payload });
const failedFetch = error => ({type: 'FAILED_TO_FETCH_DATA', error});
const getData = (id) => from(firebaseApp.database()
.ref(`users/${id}`).
.once('value')
.then((snapshot) => snapshot.val()))
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap((action) => getData(id)),
map(fetchUserFulfilled)
catchError((error) => of(failedFetch(error)))
)
这是我的史诗,但它不起作用。
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap(async (action) => {
const readData = firebaseApp.database().ref(`users/${id}`)
const myData = await readData.once('value').then((snapshot) => {
const data = snapshot.val()
// console.log(data) this works correctly
return data
})
return [fetchDataFulfilled(myData)]
}),
catchError((e) =>
of({
type: 'FAILED_TO_FETCH_DATA',
e,
}),
),
)
当我在 await 中记录数据时,它就在那里。但出于某种原因我无法将其传递给操作来实现它
错误是说:Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
但这是中间件?
所以我的主要问题是,如何等待 firebase 完成,然后将数据正确发送到我的史诗?
我认为你必须使用 rxjs
from operator
import { from } from 'rxjs';
const fetchUserFulfilled = payload => ({ type: `FETCH_USER_FULFILLED`, payload });
const failedFetch = error => ({type: 'FAILED_TO_FETCH_DATA', error});
const getData = (id) => from(firebaseApp.database()
.ref(`users/${id}`).
.once('value')
.then((snapshot) => snapshot.val()))
export const getUserDetails = (action$) =>
action$.pipe(
ofType(GET_USER_DATA),
mergeMap((action) => getData(id)),
map(fetchUserFulfilled)
catchError((error) => of(failedFetch(error)))
)