我想知道,我们可以使用Redux工具包createAsyncThunk或RTK查询在React中的firebase查询吗?
kd3sttzy1#
是的,您可以使用queryFn属性编写RTK查询端点,并使用fakeBaseQuery属性代替fetchBaseQuery属性。
queryFn
fakeBaseQuery
fetchBaseQuery
import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query' const api = createApi({ baseQuery: fakeBaseQuery(), endpoints: (build) => ({ getSomeDataFromFirebase: build.query({ queryFn(arg) { try { const result = ... // call firebase here return { data: result.something } } catch (e) { return { error: e } } }, }), }), })
bvn4nwqk2#
在redux查询中,我们通常使用fetchBaseQuery,但由于我们只是查询数据库,并且firebase没有任何put、delete、update API,因此我们使用fakeBaseQuery()
fakeBaseQuery()
import { createApi, fakeBaseQuery } from "@reduxjs/toolkit/query/react"; import {collection,doc,getDoc,getDocs} from "firebase/firestore"; //export const db = getFirestore(app) inside firebase setting import {db} from "../firebaseConfig" export const postsApi = createApi({ reducerPath: "posts", baseQuery: fakeBaseQuery(), tagTypes: ["Post"], endpoints: (builder) => ({ fetchPosts: builder.query({ // since we are using fakeBaseQuery we use queryFn async queryFn() { try { // posts is the collection name const blogRef = collection(db, "posts"); const querySnaphot = await getDocs(blogRef); let posts = []; querySnaphot?.forEach((doc) => { posts.push({ id: doc.id, ...doc.data() }); }); return { data: posts }; } catch (error) { return { error }; } }, providesTags: ["Post"], }), //***************SINGLE ITEM FETCHING*************** */ fetchSinglePost: builder.query({ async queryFn(id) { try { const docRef = doc(db, "posts", id); const snapshot = await getDoc(docRef); return { data: snapshot.data() }; } catch (error) { return { error }; } }, providesTags: ["Post"], }), }), }); export const { useFetchPostsQuery, useFetchSinglePostQuery } = postsApi;
2条答案
按热度按时间kd3sttzy1#
是的,您可以使用
queryFn
属性编写RTK查询端点,并使用fakeBaseQuery
属性代替fetchBaseQuery
属性。bvn4nwqk2#
在redux查询中,我们通常使用
fetchBaseQuery
,但由于我们只是查询数据库,并且firebase没有任何put、delete、update API,因此我们使用fakeBaseQuery()