Skip to content

Commit

Permalink
changed all uses of direct firebase querying to tanstack query hooks.
Browse files Browse the repository at this point in the history
  • Loading branch information
FrankreedX committed Mar 4, 2024
1 parent 7b02668 commit d24dea6
Show file tree
Hide file tree
Showing 21 changed files with 416 additions and 433 deletions.
13 changes: 12 additions & 1 deletion Utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ export function refToID(ref) {
return ref["_key"] ? ref["_key"]["path"]["segments"].at(-1) : "bad ref";
}

export function getUnique(array, field) {
const uniqueMap = new Map();
array.forEach((element) => {
const keyValue = element[field];
if (!uniqueMap.has(keyValue)) {
uniqueMap.set(keyValue, element);
}
});
return Array.from(uniqueMap.values());
}

export function calculateAverageProxToHole(drillSubmissions) {
const userAverages = [];
drillSubmissions.forEach((submission) => {
Expand Down Expand Up @@ -106,5 +117,5 @@ export function createOutputData(inputValues, attemptData) {
return { ...object, sid: shotNum };
});

console.log("Output Data: ", outputData);
//console.log("Output Data: ", outputData);
}
55 changes: 25 additions & 30 deletions app/content/drill/[id]/attempts/[attempt].js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { useLocalSearchParams } from "expo-router";
import { doc, getDoc } from "firebase/firestore";
import { useEffect, useState } from "react";
import {
ScrollView,
StyleSheet,
Expand All @@ -11,19 +9,39 @@ import {
import { SafeAreaView } from "react-native-safe-area-context";
import ScatterChart from "react-native-scatter-chart";
import { numTrunc } from "~/Utility";
import ErrorComponent from "~/components/errorComponent";
import Loading from "~/components/loading";
import ShotAccordion from "~/components/shotAccordion";
import db from "~/firebaseConfig";
import { useAttempts } from "~/hooks/useAttempts";
import { useDrillInfo } from "~/hooks/useDrillInfo";

function Result() {
const drillId = useLocalSearchParams()["id"];
const attemptId = useLocalSearchParams()["attempt"];
const [drillInfo, setDrillInfo] = useState({});
const [attempt, setAttempt] = useState({});
const { width } = useWindowDimensions();

const {
data: drillInfo,
isLoading: drillInfoIsLoading,
error: drillInfoError,
} = useDrillInfo(drillId);

const {
data: attempt,
isLoading: attemptIsLoading,
error: attemptError,
} = useAttempts({ attemptId });

if (drillInfoIsLoading || attemptIsLoading) {
return <Loading />;
}

if (drillInfoError || attemptError) {
return <ErrorComponent message={[drillInfoError, attemptError]} />;
}

let dots = [];
if (
Object.keys(drillInfo).length > 0 &&
Object.keys(attempt).length > 0 &&
drillInfo["outputs"].includes("sideLanding") &&
drillInfo["outputs"].includes("carryDiff")
) {
Expand All @@ -32,29 +50,6 @@ function Result() {
value["carryDiff"],
]);
}
const { width } = useWindowDimensions();
useEffect(() => {
// massive data fetching on refresh. May or may not get its data from cache
let mainOutputAttempt = "";
getDoc(doc(db, "teams", "1", "drills", drillId)).then((doc) => {
// get drill data
if (doc.exists()) {
setDrillInfo(doc.data());
console.log("got drill data", mainOutputAttempt);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
});
getDoc(doc(db, "teams", "1", "attempts", attemptId))
.then((doc) => {
setAttempt(doc.data());
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
return () => {};
}, []);

return (
<>
Expand Down
28 changes: 11 additions & 17 deletions app/content/drill/[id]/description.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,22 @@
import { useQuery } from "@tanstack/react-query";
import { Link, useLocalSearchParams } from "expo-router";
import { doc, getDoc } from "firebase/firestore";
import { Image, ScrollView } from "react-native";
import { Button, Text } from "react-native-paper";
import db from "~/firebaseConfig";
import Error from "../../../../components/error";
import Loading from "../../../../components/loading";
import Loading from "~/components/loading";
import ErrorComponent from "../../../../components/errorComponent";
import { useDrillInfo } from "../../../../hooks/useDrillInfo";

export default function Description() {
const drillId = useLocalSearchParams()["id"];

const { isPending, error, data } = useQuery({
queryKey: ["drillInfo", drillId],
queryFn: ({ queryKey }) => {
const [_key, id] = queryKey;
return getDoc(doc(db, "teams", "1", "drills", id));
},
});
const {
data: drillInfo,
error: drillInfoError,
isLoading: drillInfoIsLoading,
} = useDrillInfo(drillId);

if (isPending) return <Loading />;
if (drillInfoIsLoading) return <Loading />;

if (error) return <Error error={error.message} />;

const drillData = data?.data();
if (drillInfoError) return <ErrorComponent error={error.message} />;

return (
<ScrollView
Expand All @@ -34,7 +28,7 @@ export default function Description() {
<Text style={{ paddingBottom: 10 }} variant="headlineLarge">
Description
</Text>
<Text variant="bodySmall">{drillData.description}</Text>
<Text variant="bodySmall">{drillInfo["description"]}</Text>
<Image
source={require("~/assets/drill-description-image.jpg")}
style={{ width: "100%", maxHeight: 200, marginTop: 50 }}
Expand Down
34 changes: 11 additions & 23 deletions app/content/drill/[id]/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,25 @@ import Description from "./description";
import Leaderboard from "./leaderboard";
import Stat from "./statistics";

import { useQuery } from "@tanstack/react-query";
import { doc, getDoc } from "firebase/firestore";
import { SafeAreaView } from "react-native-safe-area-context";
import Error from "~/components/error";
import ErrorComponent from "~/components/errorComponent";
import Loading from "~/components/loading";
import db from "~/firebaseConfig";
import { useDrillInfo } from "../../../../hooks/useDrillInfo";

export default function Index() {
const [value, setValue] = React.useState("description");
const navigation = useNavigation();
const { id } = useLocalSearchParams();
const drillId = useLocalSearchParams()["id"];

console.log("ID: ", id);
const {
data: drillInfo,
error: drillInfoError,
isLoading: drillInfoIsLoading,
} = useDrillInfo(drillId);

const { isPending, error, data } = useQuery({
queryKey: ["drillInfo", id],
queryFn: ({ queryKey }) => {
const [_key, drillId] = queryKey;
console.log("drillId: ", drillId);
return getDoc(doc(db, "teams", "1", "drills", drillId));
},
});
if (drillInfoIsLoading) return <Loading />;

if (isPending) return <Loading />;

if (error) {
console.log("error: ", error);
return <Error error={error.message} />;
}

const drillData = data?.data();
if (drillInfoError) return <ErrorComponent error={drillInfoError.message} />;

const tabComponent = () => {
switch (value) {
Expand All @@ -59,7 +47,7 @@ export default function Index() {
}}
color={"#F24E1E"}
/>
<Appbar.Content title={drillData.drillType} />
<Appbar.Content title={drillInfo["drillType"]} />
</Appbar.Header>

{/* Tab system */}
Expand Down
32 changes: 17 additions & 15 deletions app/content/drill/[id]/leaderboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import { useState } from "react";
import { ScrollView, View } from "react-native";
import { Avatar, Icon, List, Text } from "react-native-paper";
import { numTrunc } from "~/Utility";
import Error from "../../../../components/error";
import Loading from "../../../../components/loading";
import { useAttempts } from "../../../../hooks/useAttempts";
import { useDrillInfo } from "../../../../hooks/useDrillInfo";
import { useUsers } from "../../../../hooks/useUsers";
import ErrorComponent from "~/components/errorComponent";
import Loading from "~/components/loading";
import { useAttempts } from "~/hooks/useAttempts";
import { useDrillInfo } from "~/hooks/useDrillInfo";
import { useUserInfo } from "~/hooks/useUserInfo";

export default function Leaderboard() {
const drillId = useLocalSearchParams()["id"];
Expand All @@ -18,9 +18,9 @@ export default function Leaderboard() {

const {
data: userInfo,
isLoading: userIsLoading,
error: userError,
} = useUsers();
userIsLoading: userIsLoading,
userError: userError,
} = useUserInfo();

const {
data: drillInfo,
Expand All @@ -32,21 +32,21 @@ export default function Leaderboard() {
data: attempts,
isLoading: attemptIsLoading,
error: attemptError,
} = useAttempts(drillId);
} = useAttempts({ drillId });

console.log("userInfo: ", userInfo);
console.log("drillInfo: ", drillInfo);
console.log("attempts: ", attempts);
//console.log("userInfo: ", userInfo);
//console.log("drillInfo: ", drillInfo);

if (userIsLoading || drillIsLoading || attemptIsLoading) {
return <Loading />;
}

if (userError || drillError || attemptError) {
let errorMessage = ", ".join([userError, drillError, attemptError]);
return <Error message={errorMessage} />;
return <ErrorComponent message={[userError, drillError, attemptError]} />;
}

// console.log("attempts: ", attempts);

const mainOutputAttempt = defaultMainOutputAttempt
? drillInfo["mainOutputAttempt"]
: customMainOutputAttempt;
Expand All @@ -60,14 +60,16 @@ export default function Leaderboard() {
drillLeaderboardAttempts[entry.uid][mainOutputAttempt] <
entry[mainOutputAttempt]
) {
drillLeaderboardAttempts[entry.uid] = { ...entry, id: id };
drillLeaderboardAttempts[entry.uid] = entry;
}
}

const orderedLeaderboard = Object.values(drillLeaderboardAttempts).sort(
(a, b) => a[mainOutputAttempt] - b[mainOutputAttempt],
);

// console.log(orderedLeaderboard[0]);

return (
<ScrollView>
<List.Section style={{ marginLeft: 20 }}>
Expand Down
68 changes: 27 additions & 41 deletions app/content/drill/[id]/statistics.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,37 @@
import { useLocalSearchParams } from "expo-router";
import { useContext, useEffect, useState } from "react";

import {
collection,
doc,
getDoc,
getDocs,
query,
where,
} from "firebase/firestore";
import { useContext } from "react";
import BarChartScreen from "~/components/barChart";
import ErrorComponent from "~/components/errorComponent";
import Loading from "~/components/loading";
import { CurrentUserContext } from "~/contexts/CurrentUserContext";
import db from "~/firebaseConfig";
import { useAttempts } from "~/hooks/useAttempts";
import { useDrillInfo } from "~/hooks/useDrillInfo";

export default function Stat() {
const drillId = useLocalSearchParams()["id"];
const [drillInfo, setDrillInfo] = useState("");
const [drillAttempts, setDrillAttempts] = useState([]);
const userId = useContext(CurrentUserContext)["currentUser"];
useEffect(() => {
// massive data fetching on refresh. May or may not get its data from cache
getDoc(doc(db, "teams", "1", "drills", drillId)).then((doc) => {
// get drill data
if (doc.exists()) {
setDrillInfo(doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
});
getDocs(
query(
collection(db, "teams", "1", "attempts"),
where("did", "==", drillId),
where("uid", "==", userId),
),
)
.then((querySnapshot) => {
// get all attempts in drill and filter only the highest score for a user
let newDrillAttempts = [];
querySnapshot.forEach((doc) => newDrillAttempts.push(doc.data()));
setDrillAttempts(newDrillAttempts);
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
return () => {};
}, []);

const {
data: drillInfo,
isLoading: drillInfoIsLoading,
drillInfoError,
} = useDrillInfo(drillId);

const {
data: drillAttempts,
isLoading: drillAttemptsIsLoading,
error: drillAttemptsError,
} = useAttempts({ drillId, userId });

if (drillInfoIsLoading || drillAttemptsIsLoading) {
return <Loading />;
}

if (drillInfoError || drillAttemptsError) {
return <ErrorComponent message={[drillInfoError, drillAttemptsError]} />;
}
// console.log(drillAttempts);

return <BarChartScreen drillData={drillAttempts} drillInfo={drillInfo} />;
}
Loading

0 comments on commit d24dea6

Please sign in to comment.