Skip to content

Commit

Permalink
Refactored State Management
Browse files Browse the repository at this point in the history
  • Loading branch information
Ruchir28 committed Aug 4, 2024
1 parent cf56a1d commit 34d4536
Show file tree
Hide file tree
Showing 12 changed files with 147 additions and 160 deletions.
52 changes: 51 additions & 1 deletion frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"react-scripts": "5.0.1",
"react-toastify": "^9.1.3",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
"web-vitals": "^2.1.4",
"zustand": "^4.5.4"
},
"scripts": {
"start": "react-scripts start",
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Home.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import React from "react";
import { useWebSocket, WebSocketStatus } from "../hooks/useWebSocket";
import withAuth from "../hoc/withAuth";
import { emitEvent, MessageType } from "@ruchir28/ws-events";
import useSpaceManager from "../hooks/useSpaceManager";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";
import useStore, {WebSocketStatus} from "../hooks/useStore";

// Define the type of the props object that will be passed to the component

// Define the component as a function that takes in the props object and returns a JSX element
const Home = () => {
const { webSocket, webSocketStatus } = useWebSocket();
const { webSocket, webSocketStatus } = useStore();
const [spaceName, setSpaceName] = React.useState<string>("");
const [joinSpace, setJoinSpace] = React.useState<string>("");
const { spaces } = useSpaceManager();
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/components/Login.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import React from "react";
import { useState } from "react";
import { BACKEND_URL } from "../constant";
import Cookies from "js-cookie";
import { Navigate } from "react-router-dom";
import useAuth, { AuthStatus } from "../hooks/useAuth";
import useStore, {AuthStatus} from "../hooks/useStore";

function Login() {
const [name, setName] = useState("");
const {isAuthenticated} = useAuth();
const {isAuthenticated,login} = useStore();
console.log("State is", isAuthenticated);

async function onSubmit(e: any) {
Expand All @@ -22,7 +21,8 @@ function Login() {
.then((res) => res.json())
.then((data) => {
console.log(data);
Cookies.set("authToken", encodeURI(data.userId));
// Cookies.set("authToken", encodeURI(data.userId));
login(encodeURI(data.userId))
})
.catch((err) => {
console.log("Login Failed");
Expand Down
7 changes: 3 additions & 4 deletions frontend/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { useNavigate } from "react-router-dom";
import { WebSocketStatus, useWebSocket } from "../hooks/useWebSocket";
import useAuth from "../hooks/useAuth";
import useStore, {WebSocketStatus} from "../hooks/useStore";

function Navbar() {

const { webSocketStatus } = useWebSocket();
const { webSocketStatus } = useStore();
const navigate = useNavigate();
const {logout} = useAuth();
const {logout} = useStore();

return (
<nav className="navbar bg-body-tertiary">
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Space.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import useSpace from "../hooks/useSpace";
import { useWebSocket } from "../hooks/useWebSocket";
import { MessageType, emitEvent } from "@ruchir28/ws-events";
import withAuth from "../hoc/withAuth";
import Question from "./Question";
import {useNavigate} from "react-router-dom"
import useStore from "../hooks/useStore";

interface SpaceProps {}

const Space: React.FC<SpaceProps> = () => {
const { spaceId } = useParams();
const { currentRound, questions, users, roundEnded } = useSpace(spaceId!);
const { webSocket, webSocketStatus } = useWebSocket();
const { webSocket, webSocketStatus } = useStore();
const [viewUsers, setViewUsers] = React.useState<boolean>(false);
const [question, setQuestion] = React.useState<string>("");
const navigate = useNavigate();
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/hoc/withAuth.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useEffect } from "react";
import useAuth, { AuthStatus } from "../hooks/useAuth";
import {useNavigate} from 'react-router-dom'
import useStore, {AuthStatus} from "../hooks/useStore";

const withAuth = <P extends object>(
WrappedComponent: React.ComponentType<P>
): React.FC<P> => {
return (props: P) => {
const {isAuthenticated} = useAuth();
const {isAuthenticated} = useStore();
const navigate = useNavigate();
useEffect(()=>{
console.log("State is",isAuthenticated);
Expand Down
62 changes: 0 additions & 62 deletions frontend/src/hooks/useAuth.ts

This file was deleted.

6 changes: 2 additions & 4 deletions frontend/src/hooks/useSpace.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { useEffect, useMemo, useState } from "react";
import { ClientMessageType, MessageType, emitEvent } from "@ruchir28/ws-events"; // Import your message types
import { useWebSocket, WebSocketStatus } from "./useWebSocket";
import { createClientHandlerManager } from "@ruchir28/ws-events";
import useAuth from "./useAuth";
import { toast } from "react-toastify";
import useStore, {WebSocketStatus} from "./useStore";

function useSpace(spaceId: string) {
const { webSocket, webSocketStatus} = useWebSocket();
const {isAuthenticated} = useAuth();
const { webSocket, webSocketStatus, isAuthenticated} = useStore();

// Example state variables
const [questions, setQuestions] = useState<Question[]>([]);
Expand Down
6 changes: 2 additions & 4 deletions frontend/src/hooks/useSpaceManager.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { useEffect, useMemo, useState } from "react";
import useAuth, { AuthStatus } from "./useAuth";
import { WebSocketStatus, useWebSocket } from "./useWebSocket";
import { ClientMessageType, emitEvent, MessageType } from "@ruchir28/ws-events";
import { createClientHandlerManager } from "@ruchir28/ws-events";
import { toast } from "react-toastify";
import useStore, {WebSocketStatus, AuthStatus} from "./useStore";
const useSpaceManager = () => {
const {isAuthenticated: authStatus} = useAuth();
const { webSocketStatus,webSocket } = useWebSocket();
const {isAuthenticated: authStatus, webSocketStatus,webSocket} = useStore();

useEffect(() => {
console.log("updated in space manager",webSocketStatus);
Expand Down
77 changes: 77 additions & 0 deletions frontend/src/hooks/useStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import {createWithEqualityFn} from 'zustand/traditional';
import { FrontEndWebSocket } from "../utils/FrontendWebSocket";
import { WEBSOCKET_URL } from "../constant";

export enum AuthStatus {
Loading = "Loading",
Authenticated = "Authenticated",
NotAuthenticated = "NotAuthenticated",
}

export enum WebSocketStatus {
Uninitialized = "Uninitialized",
Connecting = "Connecting",
Connected = "Connected",
Disconnected = "Disconnected",
}

interface State {
isAuthenticated: AuthStatus;
authToken: string | null;
webSocketStatus: WebSocketStatus;
webSocket: FrontEndWebSocket | null;
login: (token: string) => void;
logout: () => void;
initWebSocket: () => void;
closeWebSocket: () => void;
}

const useStore = createWithEqualityFn<State>((set, get) => ({
isAuthenticated: AuthStatus.Loading,
authToken: null,
webSocketStatus: WebSocketStatus.Uninitialized,
webSocket: null,
login: (token: string) => {
document.cookie = `authToken=${token}; path=/;`;
set({ authToken: token, isAuthenticated: AuthStatus.Authenticated });
get().initWebSocket();
},
logout: () => {
document.cookie = "authToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
set({ authToken: null, isAuthenticated: AuthStatus.NotAuthenticated });
get().closeWebSocket();
},
initWebSocket: () => {
const { authToken, webSocketStatus, webSocket } = get();
if (webSocket?.ws?.readyState === 0 || webSocket?.ws?.readyState === 1) return;

if (authToken && (!webSocket || webSocketStatus === WebSocketStatus.Disconnected)) {
const newWebSocket = new FrontEndWebSocket(`${WEBSOCKET_URL}`);
set({ webSocket: newWebSocket });

const handleOpen = () => set({ webSocketStatus: WebSocketStatus.Connected });
const handleError = () => set({ webSocketStatus: WebSocketStatus.Disconnected });
const handleClose = () => set({ webSocketStatus: WebSocketStatus.Disconnected });

newWebSocket.ws.addEventListener("open", handleOpen);
newWebSocket.ws.addEventListener("error", handleError);
newWebSocket.ws.addEventListener("close", handleClose);

return () => {
newWebSocket.ws.removeEventListener("open", handleOpen);
newWebSocket.ws.removeEventListener("error", handleError);
newWebSocket.ws.removeEventListener("close", handleClose);
};
}
},
closeWebSocket: () => {
const { webSocket } = get();
if (webSocket?.ws.readyState === 1) {
webSocket.ws.close();
}
set({ webSocketStatus: WebSocketStatus.Disconnected });
},
}));

export default useStore;

Loading

0 comments on commit 34d4536

Please sign in to comment.