Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a dynamic data from firestore in the function where() and also use the snap.size to count the total query to be passed in a graph?

I have this data from firestore and I wanted to retrieve it dynamically with a where() but this is the error I'm getting:

TypeError: vaccines is not a function

The user collection:

[![enter image description here][1]][1]

Below are the codes:

 const Vaccine = () => {
      const [vaccines, setVaccines] = useState([]);
      useEffect(() => {
        const unsubscribe = firestore
          .collection("vaccines")
          .onSnapshot((snapshot) => {
            const arr = [];
            snapshot.forEach((doc) =>
              arr.push({
                ...doc.data(),
                id: doc.id,
              })
            );
            setVaccines(arr);
          });
    
        return () => {
          unsubscribe();
        };
      }, []);

 
like image 962
JS3 Avatar asked Aug 28 '21 06:08

JS3


3 Answers

Preface

As highlighted in the comments on the original question, this query structure is not advised as it requires read access to sensitive user data under /users that includes private medical data.

DO NOT USE THIS CODE IN A PRODUCTION/COMMERICAL ENVIRONMENT. Failure to heed this warning will lead to someone suing you for breaches of privacy regulations.

It is only suitable for a school project (although I would a fail a student for such a security hole) or proof of concept using mocked data. The code included below is provided for education purposes, to solve your specific query and to show strategies of handling dynamic queries in React.

From a performance standpoint, in the worst case scenario (a cache miss), you will be billed one read, for every user with at least one dose of any vaccine, on every refresh, for every viewing user. Even though your code doesn't use the contents of any user document, your code must download all of this data too because the Client SDKs do not support the select() operator.

For better security and performance, perform this logic server-side (e.g. Cloud Function, a script on your own computer, etc) and save the results to a single document that can be reused by all users. This will allow you to properly tighten access to /users. It also significantly simplifies the code you need to display the graphs and live statistics on the client-side.

useEffect

As stated by the React documentation on the Rules of hooks:

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

The documentation further elaborates that React relies on the order in which Hooks are called, which means that you can't have hook definitions behind conditional logic where their order and quantity changes between renders. If your hooks rely on some conditional logic, it must be defined inside of the hook's declaration.

As an example, if you have an effect that relies on other data, with this logic:

const [userProfile, setUserProfile] = useState();
const [userPosts, setUserPosts] = useState(null);

useEffect(() => {
  // get user profile data and store in userProfile
}, []);

if (userProfile) {
  useEffect(() => {
    // get user post list and store in userPosts
  }, [userProfile]);
}

you need to instead use:

const [userProfile, setUserProfile] = useState();
const [userPosts, setUserPosts] = useState(null);

useEffect(() => {
  // get user profile data and store in userProfile
}, []);

useEffect(() => {
  if (!userProfile) {
    // not ready yet/signed out
    setUserPosts(null);
    return;
  }
  
  // get user post list and store in userPosts
}, [userProfile]);

Similarly, for arrays:

someArray && someArray.forEach((entry) => {
  useEffect(() => {
    // do something with entry to define the effect
  }, /* variable change hooks */);
});

should instead be:

useEffect(() => {
  if (!someArray) {
    // not ready yet
    return;
  }
  
  const cleanupFunctions = [];
  someArray.forEach((entry) => {
    // do something with entry to define an effect

    cleanupFunctions.push(() => {
      // clean up the effect
    });
  });

  // return function to cleanup the effects created here
  return () => {
    cleanupFunctions.forEach(cleanup => cleanup());
  }
}, /* variable change hooks */);

Because this looks a lot like lifecycle management, you are actually better off replacing it with nested components rather than using hooks, like so:

return (
  <> // tip: React.Fragment shorthand (used for multiple top-level elements)
    {
      someArray && someArray
        .map(entry => {
          return <Entry key={entry.key} data={entry.data} />
        })
    }
  </>
);

Adapting to your code

Note: The code here doesn't use onSnapshot for the statistics because it would cause a rerender every time a new user is added to the database.

const getVaccineStats = (vaccineName) => {
  const baseQuery = firestore
    .collection("users")
    .where("doses.selectedVaccine", "==", vaccine);
      
  const oneDoseQueryPromise = baseQuery
    .where("doses.dose1", "==", true)
    .where("doses.dose2", "==", false)
    .get()
    .then(querySnapshot => querySnapshot.size);

  const twoDoseQueryPromise = baseQuery
    .where("doses.dose1", "==", true)
    .where("doses.dose2", "==", true)
    .get()
    .then(querySnapshot => querySnapshot.size);

  return Promise.all([oneDoseQueryPromise, twoDoseQueryPromise])
    .then(([oneDoseCount, twoDoseCount]) => ({ // tip: used "destructuring syntax" instead of `results[0]` and `results[1]`
      withOneDose: oneDoseCount,
      withTwoDoses: twoDoseCount
    }));
};


const Vaccine = () => {
  const [vaccines, setVaccines] = useState();
  const [vaccineStatsArr, setVaccineStatsArr] = useState([]);
  
  // Purpose: Collect vaccine definitions and store in `vaccines`
  useEffect(() => {
    return firestore  // tip: you can return the unsubscribe function from `onSnapshot` directly
      .collection("vaccines")
      .onSnapshot({ // tip: using the Observer-like syntax, allows you to handle errors
        next: (querySnapshot) => {
          const vaccineData = []; // tip: renamed `arr` to indicate what the data contains
          querySnapshot.forEach((doc) =>
            vaccineData.push({
              ...doc.data(),
              id: doc.id,
            });
          );
          setVaccines(vaccineData);
        }),
        error: (err) => {
          // TODO: Handle database errors (e.g. no permission, no connection)
        }
      });
  }, []);

  // Purpose: For each vaccine definition, fetch relevant statistics
  //          and store in `vaccineStatsArr`
  useEffect(() => {
    if (!vaccines || vaccines.length === 0) {
      return; // no definitions ready, exit early
    }

    const getVaccineStatsPromises = vaccines
      .map(({ vaccine }) => [vaccine, getVaccineStats(vaccine)]);
    // tip: used "destructuring syntax" on above line
    //      (same as `.map(vaccineInfo => [vaccineInfo.vaccine, getVaccineStats(vaccineInfo.vaccine)]);`)
    
    let unsubscribed = false;
      
    Promise.all(getVaccineStatsPromises)
      .then(newVaccineStatsArr => {
        if (unsubscribed) return; // unsubscribed? do nothing
        setVaccineStatsArr(newVaccineStatsArr);
      })
      .catch(err => {
        if (unsubscribed) return; // unsubscribed? do nothing
        // TODO: handle errors
      });

    return () => unsubscribed = true;
  }, [vaccines]);

  if (!vaccines) // not ready? hide element
    return null;

  if (vaccines.length === 0) // no vaccines found? show error
    return (<span class="error">No vaccines found in database</span>);

  if (vaccineStatsArr.length === 0) // no stats yet? show loading message
    return (<span>Loading statistics...</span>);

  return (<> // tip: React.Fragment shorthand
    {
      vaccineStatsArr.map(([name, stats]) => {
        // this is an example component, find something suitable
        // the `key` property is required
        return (<BarGraph
          key={name}
          title={`${name} Statistics`}
          columns={["One Dose", "Two Doses"]}
          data={[stats.withOneDose, stats.withTwoDoses]}
        />);
      });
    }
  </>);
};

export default Vaccine;

Live Statistics

If you want your graphs to be updated live, you need "zip together" the two snapshot listeners into one, similar to the rxjs combineLatest operator. Here is an example implementation of this:

const onVaccineStatsSnapshot => (vaccine, observerOrSnapshotCallback, errorCallback = undefined) => {
  const observer = typeof observerOrCallback === 'function'
    ? { next: observerOrSnapshotCallback, error: errorCallback }
    : observerOrSnapshotCallback;
  
  let latestWithOneDose,
    latestWithTwoDoses,
    oneDoseReady = false,
    twoDosesReady = false;

  const fireNext = () => {
    // don't actually fire event until both counts have come in
    if (oneDoseReady && twoDosesReady) {
      observer.next({
        withOneDose: latestWithOneDose,
        withTwoDoses: latestWithTwoDoses
      });
    }
  };
  const fireError = observer.error || (err) => console.error(err);

  const oneDoseUnsubscribe = baseQuery
    .where("doses.dose1", "==", true)
    .where("doses.dose2", "==", false)
    .onSnapshot({
      next: (querySnapshot) => {
        latestWithOneDose = querySnapshot.size;
        oneDoseReady = true;
        fireNext();
      },
      error: fireError
    });

  const twoDoseUnsubscribe = baseQuery
    .where("doses.dose1", "==", true)
    .where("doses.dose2", "==", true)
    .onSnapshot({
      next: (querySnapshot) => {
        latestWithTwoDoses = querySnapshot.size;
        twoDosesReady = true;
        fireNext();
      },
      error: fireError
    });

  return () => {
    oneDoseUnsubscribe();
    twoDoseUnsubscribe();
  };
}

You could rewrite the above function to make use of useState, but this would unnecessarily cause components to rerender when they don't need to.

Usage (direct):

const unsubscribe = onVaccineStatsSnapshot(vaccineName, {
  next: (statsSnapshot) => {
    // do something with { withOneDose, withTwoDoses } object
  },
  error: (err) => {
    // TODO: error handling
  }
);

or

const unsubscribe = onVaccineStatsSnapshot(vaccineName, (statsSnapshot) => {
  // do something with { withOneDose, withTwoDoses } object
});

Usage (as a component):

const VaccineStatsGraph = (vaccineName) => {
  const [stats, setStats] = useState(null);

  useEffect(() => onVaccineStatsSnapshot(vaccineName, {
    next: (newStats) => setStats(newStats),
    error: (err) => {
      // TODO: Handle errors
    }
  }, [vaccineName]);

  if (!stats)
    return (<span>Loading graph for {vaccineName}...</span>);

  return (
    <BarGraph
      title={`${name} Statistics`}
      columns={["One Dose", "Two Doses"]}
      data={[stats.withOneDose, stats.withTwoDoses]}
    />
  );
}
like image 74
samthecodingman Avatar answered Oct 21 '22 07:10

samthecodingman


vaccines is an array and not a function. You are trying to run a map on vaccines. Try refactoring your code to this:

 vaccines &&
      vaccines.map((v, index) => {
        // ...
      })

Also do check: How to call an async function inside a UseEffect() in React?

like image 2
Dharmaraj Avatar answered Oct 21 '22 06:10

Dharmaraj


here is the code, that works for you:

function DatafromFB() { 

    const[users, setUsers] = useState({});

    useEffect(()=>{
        const fetchVaccine = async () => {
          try {
            const docs = await db.collection("vaccines").get();;
            docs.forEach((doc) => {
                doc.data().vaccineDetails
                .forEach(vaccineData=>{
                 fetchUsers(vaccineData.vaccine)
                })
            })
          } catch (error) {
            console.log("error", error);
          }
        }

        const fetchUsers = async (vaccine)=>{
          try {
            const docs = await db.collection("users")
            .where("doses.selectedVaccine", "==", vaccine).get();
            docs.forEach(doc=>{
                console.log(doc.data())
                setUsers(doc.data());
            })
          }catch(error){
            console.log("error", error);
         }
        }

        fetchVaccine();

      },[])
    return (
        <div>
            <h1>{users?.doses?.selectedVaccine}</h1>
        </div>
    )
}
export default DatafromFB
like image 2
Murali Kollati Avatar answered Oct 21 '22 07:10

Murali Kollati