Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

reactjs - React/Firebase, when i try to setState the data im getting from firecloud i get thousands of console.logs out

I made login/register form and once u register, user's data is sent to cloud Firestore, then I retrieve it using 'users/${users.uid}. When I console.log it I get what I want an object file with users data, but when I try to put it into setUsersData(user.data()) and console.log it I get thousands of logs, yet if I go deeper and console.log(email or display name from user) I get it called like it should just on rerender. And I have no idea why I can't just pass whole data.

import 'firebase/auth';
import 'firebase/firestore';
import firebase from 'firebase/app';

const firebaseConfig = {
  apiKey: '...',
  authDomain: '...',
  projectId: '...',
  storageBucket: '...',
  messagingSenderId: '...',
  appId: '...',
  measurementId: '...',
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

export const auth = firebase.auth();
export const firestore = firebase.firestore();

// export const getUsersData = async (userAuth) => {
//   const userData = firestore.doc(`users/${userAuth.uid}`)
//   const snapShot = await userData.get();

// }

export const createUserProfileDocument = async (userAuth) => {
  if (!userAuth) return;

  const x = firestore.doc(`users/${userAuth.uid}`);
  const snapShot = await x.get();
  const xData = snapShot.data();

  if (!snapShot.exists) {
    const { email, displayName } = userAuth;
    const createdAt = new Date();
    x.set({
      email,
      displayName,
      createdAt,
    });
  }
  return xData;
};

export const googleAuth = () => {
  const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(googleAuthProvider);
};

export default firebase;

This registers user.

const checkPasswords = async () => {
  if (regConfirmPassword !== regPassword) {
    setVisible('');
  } else {
    try {
      const { user } = await auth.createUserWithEmailAndPassword(regEmail, regPassword);

      user.updateProfile({ displayName: userName });
    } catch (error) {
      console.log(error);
      if (error.code === 'auth/email-already-in-use') {
        setEmailPlaceHolder('Email already in use');
      }
    }
  }
};

And this is App.js file

function App() {
  const BASE_URL = "https://dummyapi.io/data/api";
  const APP_ID = "";

  const [data, setData] = useState([]);
  const [pages, setPages] = useState(0);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const [isLogin, setIsLogin] = useState(false);
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    // getData();
  }, [pages]);

  const getData = async () => {
    try {
      const response = await fetch(`${BASE_URL}/post?page=${pages}`, {
        headers: { "app-id": APP_ID },
      });
      const x = await response.json();
      setData([...data, ...x.data]);
      setLoading(false);
    } catch (error) {
      setHasError(true);
      console.log(error);
    }
  };

  useEffect(() => {
    onAuthChange();
    return () => {
      onAuthChange();
    };
  }, [isLogin]);

const onAuthChange = auth.onAuthStateChanged(async (userAuth) => {
  if (userAuth) {
    setIsLogin(true);
    const y = await createUserProfileDocument(userAuth);
    setUserData(y);
    setUserData(y.email); // this way works fine and logs out just once.
    console.log(y); // if i console y it is as expected.
  } else {
    setIsLogin(false);
  }
});

console.log(userData); // this one gets console.log'ed thousands of times.
question from:https://stackoverflow.com/questions/65951576/react-firebase-when-i-try-to-setstate-the-data-im-getting-from-firecloud-i-get

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...