Home > Software design >  React & Firebase Global State
React & Firebase Global State

Time:02-01

I'm using react-firebase-hook , and I'm trying to check if the user is admin or not, and I want to it to be a global state where I don't have to add this code in every and each component to check if the user is admin or not, here is the code..

import { useState, useEffect } from 'react';
import { query, collection, getDocs, where } from "firebase/firestore";
import { auth, db } from "../../config/fbConfig";
import { useAuthState } from "react-firebase-hooks/auth";
const CreateAnn = () => {
    const [ann, setAnn] = useState(''); // ignore this
    const [admin, setAdmin] = useState(false);
    const [user] = useAuthState(auth);
    const fetchAdmin = async () => {
        try {
          const q = query(collection(db, "users"), where("uid", "==", user?.uid));
          const doc = await getDocs(q);
          const data = doc.docs[0].data();
          if(data.admin === true) {
            setAdmin(true);
          }
          else { setAdmin(false); }
        } catch (err) {
          // do nothing
        }
    };
useEffect(() => {
    fetchAdmin();
});

I want to have this as a global state, tried to useContext but i think I'm using it the wrong way, so anyone can help?

CodePudding user response:

You are correct to use a context, however, you might use it wrong as you said. You should set up a context that handles the currently logged in user. In this context you can also fetch the extra details of the user from the user collection.

Also, you can grab the user directly with ID instead of where:

const docRef = doc(db, "users", user.uid);
const docSnap = await getDoc(docRef);
const data  = docSnap.exists ? docSnap.data() : undefined

Follow this link to set up the context of auth correct.

https://dev.to/dchowitz/react-firebase-a-simple-context-based-authentication-provider-1ool

  • Related