first commit for refactored project
This commit is contained in:
54
ax3Client/src/Hooks/useContext/appContext.js
Executable file
54
ax3Client/src/Hooks/useContext/appContext.js
Executable file
@@ -0,0 +1,54 @@
|
||||
import React, { createContext, useContext, useEffect, useReducer } from "react";
|
||||
import { useGroupReducer } from "../useReducer/reducers";
|
||||
import { AuthContext } from "../../Context/AuthProvider";
|
||||
import { db } from "../../firebase.js";
|
||||
import {
|
||||
collection,
|
||||
getDocs,
|
||||
query,
|
||||
where,
|
||||
onSnapshot,
|
||||
} from "firebase/firestore";
|
||||
|
||||
const initialState = {
|
||||
group: undefined,
|
||||
};
|
||||
|
||||
const AppContext = createContext({
|
||||
state: initialState,
|
||||
dispatch: () => null,
|
||||
});
|
||||
|
||||
const AppProvider = ({ children }) => {
|
||||
const { currentUserEmail } = useContext(AuthContext);
|
||||
const [appState, appDispatch] = useReducer(useGroupReducer, initialState);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof currentUserEmail === "undefined") {
|
||||
return;
|
||||
}
|
||||
if (!currentUserEmail) {
|
||||
appDispatch({ type: "DELETE_GROUP" });
|
||||
return;
|
||||
}
|
||||
return onSnapshot(
|
||||
query(collection(db, "users"), where("email", "==", currentUserEmail)),
|
||||
(snapshot) => {
|
||||
const doc = snapshot.docs[0];
|
||||
if (typeof doc === "undefined") {
|
||||
appDispatch({ type: "DELETE_GROUP" });
|
||||
} else {
|
||||
appDispatch({ type: "CREATE_GROUP", payload: doc.data() });
|
||||
}
|
||||
}
|
||||
);
|
||||
}, [currentUserEmail]);
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={{ appState, appDispatch }}>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { AppContext, AppProvider };
|
||||
Reference in New Issue
Block a user