简体   繁体   中英

How to integrate redux into firebase firestore?

I am able to get the data in categoryMap from firebase firestore but I want to save the data in a state and then share that state between components using redux toolkit. Should I create action creators in the code below or should I use react's useState hook and then apply redux on top of that?

Here is the code snippet of the data I get from firestore:

export const getCategoriesAndDocuments = async () => {
  const collectionRef = collection(db, 'categories');
  const q = query(collectionRef);
  const querySnapshot = await getDocs(q);
  const categoryMap = querySnapshot.docs.reduce((acc, docSnapshot) => {
    const { title, items } = docSnapshot.data();

    acc[title.toLowerCase()] = items;
    return acc;
  }, {});
};

You can directly store your data in your redux store. Since redux store is A store holds the whole state tree of your application you don't need to add an extra state.

I know this is an old question, but if anyone ends up here looking for an answer:

Besides what was suggested by Tolunay Özdemir, you can also use RTK Query to fetch data from Firestore. This way you can benefit from its caching capabilities and use...Query, use...Mutation hooks if you want to use them.

You can do something like the following, using fakeBaseQuery() as baseQuery , and queryFn instead of regular query :

import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react';
import { collection, doc, getDocs } from 'firebase/firestore';
import { db } from '../../firebase';

export const getCategoriesAndDocuments = async () => {
  const collectionRef = collection(db, 'categories');
  const q = query(collectionRef);
  const querySnapshot = await getDocs(q);
  const categoryMap = querySnapshot.docs.reduce((acc, docSnapshot) => {
    const { title, items } = docSnapshot.data();
    acc[title.toLowerCase()] = items;
    return acc;
  }, {});
  return categoryMap;
};

export const api = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: (builder) => ({
    fetchData: builder.query({
      async queryFn() {
        try {
          const data = await getCategoriesAndDocuments();
          return { data };
        } catch (error) {
          console.error(error.message);
          return { error: error.message };
        }
      },
    }),
  }),
});

export const { useFetchDataQuery } = api;

I wrote a blog post if you'd like more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM