redux 关于从RTK查询获取数据到Firebase实时数据库

rta7y2nd  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(141)

我目前正尝试使用RTK查询从Firebase实时数据库获取数据。但是,由于返回的值不正确,此处的代码给了我一个错误。如果有人知道这一点,我将不胜感激,如果你能将代码更正为正确的代码。

import { createApi, fakeBaseQuery } from "@reduxjs/toolkit/query/react";
import { onValue, ref } from "firebase/database";
import { db } from "libs/firebase";

export const userApi = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: builder => ({
    getUser: builder.query({
      queryFn(uid) {
        try {
          onValue(ref(db, `users/user${uid}`), snapshot => {
            return { data: snapshot.val() };
          });
        } catch (e) {
          return { error: e };
        }
      },
    }),
  }),
});

export const { useGetUserQuery } = userApi;
import { configureStore } from "@reduxjs/toolkit";
import { userApi } from "./apiSlice";

export const store = configureStore({
  reducer: {
    [userApi.reducerPath]: userApi.reducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(userApi.middleware),
});
const { data: user, error, isLoading, isSuccess } = useGetUserQuery(1);
console.log(user);

error message

ogq8wdun

ogq8wdun1#

尝试一些沿着于

export const userApi = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: (builder) => ({
    getUser: builder.query({
      async queryFn(uid) {
        try {
          const data = await new Promise((resolve, reject) =>
            onValue(
              ref(db, `users/user${uid}`),
              (snapshot) => resolve(snapshot.toJSON()),
              reject
            )
          );
          return { data };
        } catch (e) {
          return { error: e };
        }
      },
    }),
  }),
});

相关问题