Search code examples
javascriptreactjsexporeact-context

How to fetch data only if or when the user is logged in with React Js Context API?


The code below runs as soon as the app startbut I would like to fetch the data in my collection only when the user login or if the user is logged in. How can i do that ?.

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>
  );
};```

Solution

  • In you useEffect you can add auth check and call 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]);