[英]React & Firebase Global State
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..我正在使用react-firebase-hook ,我正在尝试检查用户是否是管理员,我希望它是一个全局的 state ,我不必在每个组件中添加此代码检查用户是否是管理员,这里是代码..
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?我想将其作为全局 state,尝试使用 useContext 但我认为我使用它的方式不对,所以有人可以提供帮助吗?
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 :此外,您可以直接使用 ID 而不是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.按照此链接设置 auth correct 的上下文。
https://dev.to/dchowitz/react-firebase-a-simple-context-based-authentication-provider-1ool https://dev.to/dchowitz/react-firebase-a-simple-context-based-authentication-provider-1ool
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.