简体   繁体   中英

How can I select specific screens to show to different types of users in Expo/Firebase?

I'm creating an Expo application (using Firebase as the backend service) with three different types of users, and I'm trying to restrict certain users from seeing other screens.

For example, there is an admin user type, which should have access to a screen that adds/deletes other users. The other user types should not be able to see or access this screen. I'm also using react-navigation to create a bottom tab navigator, and I want to restrict some tabs from being shown to other user types.

Currently, all user information is saved in a Firestore collection. However, I'm not sure where or when I should be fetching the user data. Should I do this upon login or when the app is first loaded, perhaps? I'm currently trying to do this in my firebase.js file, but I'm running into some problems with the async properties of getDoc.

// Import the functions you need from the SDKs you need
import { getAuth } from 'firebase/auth';
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, getDoc } from 'firebase/firestore';

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
    // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth();
const user = auth.currentUser;

getDoc(doc(db, 'users', user.uid))
    .then((userSnap) => {
        const userType = userSnap.data().type;
    })
    .catch((err) => console.log(err));

export { auth, userType, app, db };

You could store the user type in a state in the file and then conditionally render the screens depending on what the user type is, so you would have something like this:

 const [userType, setUserType] = useState(); switch (userType) { case 'anonymous': return anonScreens.map(({name, component}) => <Screen name={name} />) case 'authorized': return authorizedScreens.map(({name, component}) => <Screen name={name} />) case 'admin': return adminScreens.map(({name, component}) => <Screen name={name} />) }

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