Skip to content

Commit

Permalink
Fixed context bug with GatherWordsProvided added it too I guess
Browse files Browse the repository at this point in the history
  • Loading branch information
Rice-Tech committed Jan 28, 2024
1 parent c348da0 commit d438a2f
Show file tree
Hide file tree
Showing 5 changed files with 156 additions and 84 deletions.
8 changes: 2 additions & 6 deletions src/components/WordItem.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { Text } from "@react-three/drei";
import {
ContactForcePayload,
RapierRigidBody,
RigidBody,
} from "@react-three/rapier";
import { RapierRigidBody, RigidBody } from "@react-three/rapier";
import { useCallback, useRef, useState } from "react";
import * as THREE from "three";
import { state } from "@/MiniGame1";
Expand All @@ -19,7 +15,7 @@ interface WordItemProps {
export function WordItem({ position, color, words, boxId }: WordItemProps) {
const api = useRef<RapierRigidBody>(null);
const [wordIndex, setWordIndex] = useState(0);
const contactForce = useCallback((payload: ContactForcePayload) => {
const contactForce = useCallback(() => {
if (boxId === 1) {
state.api.soundEnemy1();
state.api.changeEnemy1Text();
Expand Down
116 changes: 116 additions & 0 deletions src/contexts/GatherWordsContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import {
createContext,
useState,
useContext,
useEffect,
ReactNode,
} from "react";
import { WordInput } from "@/components/StoryEngine";
import {
setDoc,
doc,
query,
collection,
where,
onSnapshot,
} from "firebase/firestore";
import { db } from "../firebase";
import { useAuth } from "../contexts/AuthContext";
import { useParams } from "react-router-dom";

// Define the context interface
interface GatherWordsContextType {
contextWords: WordInput[];
setContextWords: React.Dispatch<React.SetStateAction<WordInput[]>>;
}

// Create the context
const initialContextValue: GatherWordsContextType = {
contextWords: [],
setContextWords: () => {}, // Placeholder function
};
const GatherWordsContext =
createContext<GatherWordsContextType>(initialContextValue);

interface Props {
children: ReactNode;
}

// Create a provider component
export const GatherWordsProvider = ({ children }: Props) => {
const [contextWords, setContextWords] = useState<WordInput[]>([]);
const { currentUser } = useAuth();
const params = useParams();
useEffect(() => {
console.log("contextWords changed");
console.table(contextWords);
}, [contextWords]);
useEffect(() => {
if (!currentUser) {
console.log(
"You must be logged in to play a game or at least have a valid session."
);
return;
}
const uid = currentUser.uid;
const joinRoom = () => {
const ref = `rooms/${params.gameId}/users/${uid}`;
console.log(ref);
setDoc(doc(db, ref), {
uid: uid,
timeJoined: new Date().getTime(),
status: "active",
});
};
const watchWords = () => {
const ref = `rooms/${params.gameId}/words`;
const q = query(collection(db, ref), where("user", "==", uid));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const wordSnaps: WordInput[] = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
wordSnaps.push({
word: data.word,
partOfSpeech: data.partOfSpeech,
refPath: doc.ref.path,
index: data.index,
status: data.status,
user: data.user,
});
});
console.log("ContextWOrds");
console.table(contextWords);
setContextWords((prev) => {
console.log(prev);
console.log(wordSnaps);
return wordSnaps;
});
});

return unsubscribe;
};

joinRoom();
const unsubscribe = watchWords();
return unsubscribe;
}, [currentUser]);
const value = {
contextWords: contextWords,
setContextWords: setContextWords,
};
return (
<GatherWordsContext.Provider value={value}>
{children}
</GatherWordsContext.Provider>
);
};

// Custom hook to use the context
export const useGatherWords = () => {
const context = useContext(GatherWordsContext);
if (!context) {
throw new Error("useGatherWords must be used within a GatherWordsProvider");
}
return context;
};
export default GatherWordsContext;
7 changes: 6 additions & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import About from "./routes/About";
import HostGame from "./routes/HostGame";
import PlayGame from "./routes/PlayGame";
import MiniGame1 from "./MiniGame1";
import { GatherWordsProvider } from "./contexts/GatherWordsContext";

const router = createBrowserRouter([
{
Expand All @@ -30,7 +31,11 @@ const router = createBrowserRouter([
},
{
path: "/game/:gameId/play",
element: <PlayGame />,
element: (
<GatherWordsProvider>
<PlayGame />
</GatherWordsProvider>
),
},
{
path: "/minigame1",
Expand Down
24 changes: 13 additions & 11 deletions src/routes/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { FormEvent } from "react";

import { useNavigate } from "react-router-dom";
import { auth, db } from "../firebase";
import { collection, addDoc, query, where, getDocs } from "firebase/firestore";
import { collection, addDoc } from "firebase/firestore";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
Expand All @@ -17,14 +17,14 @@ const Home = () => {
);
return 2;
}
const queryExistingRoom = async () => {
const q = query(collection(db, "rooms"), where("hostUID", "==", uid));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
};
// const queryExistingRoom = async () => {
// const q = query(collection(db, "rooms"), where("hostUID", "==", uid));
// const querySnapshot = await getDocs(q);
// querySnapshot.forEach((doc) => {
// // doc.data() is never undefined for query doc snapshots
// console.log(doc.id, " => ", doc.data());
// });
// };

const createNewRoom = async () => {
const roomDoc = await addDoc(collection(db, "rooms"), {
Expand All @@ -35,7 +35,7 @@ const Home = () => {
});
return roomDoc.id;
};
queryExistingRoom();
//queryExistingRoom();
const gameId = await createNewRoom();
navigate(`/game/${gameId}`);
};
Expand All @@ -47,7 +47,9 @@ const Home = () => {
};
return (
<>
<h1 className="text-center text-4xl font-semibold leading-none tracking-tight">Tumblewords</h1>
<h1 className="text-center text-4xl font-semibold leading-none tracking-tight">
Tumblewords
</h1>
<div className=" flex-col w-1/3 aspect-square m-auto justify-around">
<Card>
<CardHeader>
Expand Down
85 changes: 19 additions & 66 deletions src/routes/PlayGame.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
setDoc,
doc,
query,
collection,
where,
onSnapshot,
} from "firebase/firestore";
import { setDoc, doc } from "firebase/firestore";
import { db } from "../firebase";
import { useAuth } from "../contexts/AuthContext";
import { WordInput } from "../components/StoryEngine";
import WordInputs from "../components/WordInputs";
import { Button } from "@/components/ui/button";
import {
Expand All @@ -20,69 +11,31 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
useGatherWords,
} from "@/contexts/GatherWordsContext";

const PlayGame = () => {
const params = useParams();
const { currentUser } = useAuth();
const [wordAssignments, setWordAssignments] = useState<WordInput[]>([]);
const [status, setStatus] = useState("collectwords");
useEffect(() => {
if (!currentUser) {
console.log(
"You must be logged in to play a game or at least have a valid session."
);
return;
}
const uid = currentUser.uid;
const joinRoom = async () => {
const ref = `rooms/${params.gameId}/users/${uid}`;
console.log(ref);
await setDoc(doc(db, ref), {
uid: uid,
timeJoined: new Date().getTime(),
status: "active",
});
};
const watchWords = () => {
const ref = `rooms/${params.gameId}/words`;
const q = query(collection(db, ref), where("user", "==", uid));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const wordSnaps: WordInput[] = [];
querySnapshot.forEach((doc) => {
const data = doc.data();
wordSnaps.push({
word: data.word,
partOfSpeech: data.partOfSpeech,
refPath: doc.ref.path,
index: data.index,
status: data.status,
user: data.user,
});
});
setWordAssignments(wordSnaps);
});

return unsubscribe;
};
const { contextWords, setContextWords } = useGatherWords();
useEffect(()=>{
console.log("contextWords changed")
console.table(contextWords)
},[contextWords])

joinRoom();
const unsubscribe = watchWords();
return unsubscribe;
}, [currentUser]);
const handleInputChange = (
e: React.ChangeEvent<HTMLInputElement>,
index: number
) => {
const newWordInputs = [...wordAssignments];
const newWordInputs = [...contextWords];
newWordInputs.filter((item) => {
console.table(item);
console.log(index);
return item.index == index;
})[0].word = e.target.value;
setWordAssignments(newWordInputs);
setContextWords(newWordInputs);
};
const handleSubmitWords = async () => {
wordAssignments.forEach((assignedWord) => {
contextWords.forEach((assignedWord) => {
if (!assignedWord.refPath) {
return;
}
Expand All @@ -105,13 +58,13 @@ const PlayGame = () => {
<CardDescription>ID: {params.gameId}</CardDescription>
</CardHeader>
<CardContent>
<WordInputs
wordsList={wordAssignments}
onChange={handleInputChange}
/>
<Button onClick={handleSubmitWords}>
{status == "submitted" ? "Resubmit" : "Submit words"}
</Button>
<WordInputs
wordsList={contextWords}
onChange={handleInputChange}
/>
<Button onClick={handleSubmitWords}>
{status == "submitted" ? "Resubmit" : "Submit words"}
</Button>
</CardContent>
</Card>
</div>
Expand Down

0 comments on commit d438a2f

Please sign in to comment.