Как извлекать данные, только если или когда пользователь вошел в систему с помощью контекстного API React Js?

#javascript #reactjs #expo #context-api

#javascript #reactjs #выставка #реагировать-контекст

Вопрос:

Приведенный ниже код запускается сразу после запуска приложения, но я хотел бы получать данные в моей коллекции только при входе пользователя в систему или при входе пользователя в систему. Как я могу это сделать ?.

 import React, { createContext, useState, useEffect } from "react";

import useAuthentication from "./../hooks/useAuthentication";
import * as firebase from "firebase";
import "firebase/firebase-firestore";

export const RequestContext = createContext();

export const RequestProvider = (props) => {
  const [richieste, setRichieste] = useState([]);
  const [inCaricamento, setInCaricamento] = useState(true);
  const auth = useAuthentication();

  useEffect(() => {
    const firestoreCall = firebase
      .firestore()
      .collection("richieste")
      /*  .where("userId", "==", props.loggedIn.uid) */

      .onSnapshot((snapshot) => {
        const newRichieste = snapshot.docs.map((richiesta) => ({
          id: richiesta.id,
          ...richiesta.data(),
        }));
        let nuoveRichieste = newRichieste.sort(function (a, b) {
          return a.timestamp - b.timestamp;
        });

        setRichieste(nuoveRichieste.reverse());
        setInCaricamento(false);
      });

    return () => firestoreCall;
  }, []);

  return (
    <RequestContext.Provider value={[richieste, setRichieste]}>
      {props.children}
    </RequestContext.Provider>
  );
};```
  

Ответ №1:

В useEffect вы можете добавить проверку подлинности и вызвать firestore.

 useEffect(() => {
    let firestoreCall;
    if(auth) {
    firestoreCall  = firebase
      .firestore()
      .collection("richieste")
      /*  .where("userId", "==", props.loggedIn.uid) */

      .onSnapshot((snapshot) => {
        const newRichieste = snapshot.docs.map((richiesta) => ({
          id: richiesta.id,
          ...richiesta.data(),
        }));
        let nuoveRichieste = newRichieste.sort(function (a, b) {
          return a.timestamp - b.timestamp;
        });

        setRichieste(nuoveRichieste.reverse());
        setInCaricamento(false);
      });  
    }
    

    return () => {
        firestoreCall?.();
    };
  }, [auth]);