reactjs 是否可以在React中使用带有Redux工具包的firebase查询或RTK查询?

niwlg2el  于 2022-12-18  发布在  React
关注(0)|答案(2)|浏览(147)

我想知道,我们可以使用Redux工具包createAsyncThunk或RTK查询在React中的firebase查询吗?

kd3sttzy

kd3sttzy1#

是的,您可以使用queryFn属性编写RTK查询端点,并使用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 }
        }
      },
    }),
  }),
})
bvn4nwqk

bvn4nwqk2#

在redux查询中,我们通常使用fetchBaseQuery,但由于我们只是查询数据库,并且firebase没有任何put、delete、update API,因此我们使用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;

相关问题