Home > Software engineering >  How to set useState by checking User data in Firebase
How to set useState by checking User data in Firebase

Time:04-22

I can't seem to figure out how to set useState after querying Firebase. Basically, I need BOX to be equal "public URL" for everyone except for admin.

import { auth } from "../firebase";
...
  const [BOX, setBox] = useState('');
  useEffect(() => {
if (auth.currentUser?.email === "[email protected]") {
  setBox("https://admin/link");
   } else {
     setBox("https://public/link");
   }
 },[auth]);

Errors are always different. Sometimes it returns "...empty link", sometimes "network request failed". Sometimes it does show the correct data, but it runs into one of the errors when I refresh the screen.

Here is my firebase file

// Import the functions you need from the SDKs you need
import * as firebase from "firebase";
import '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
const firebaseConfig = {
...
};

// Initialize Firebase

let app;
if (firebase.apps.length === 0) {
    app = firebase.initializeApp(firebaseConfig);
} else {
    app = firebase.app()
}

const auth = firebase.auth();
const dbFirebase = app.firestore();

export {auth, dbFirebase};

CodePudding user response:

You can not use hook inside an if statement...

 const [box, setBox] = useState('');
  
useEffect(() => {
    if (auth.currentUser?.email === "[email protected]") {
      setBox("https://admin/link");
       } else {
         setBox("https://public/link");
       }
 },[auth]);
  

CodePudding user response:

For firebase 9 you will need to configure it like below:

import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'

const firebaseConfig = {...}

initializeApp(firebaseConfig)

export const auth = getAuth()
  • Related