From 1d8dc0ec7a28b145af6a8fd7ca57d50762a3d1a0 Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Sat, 20 Jul 2024 13:06:53 +0200 Subject: [PATCH] Create Project context --- .../contexts/Project/ProjectContext.jsx | 59 +++++++++++++++++++ .../Dashboard/contexts/Project/index.js | 1 + 2 files changed, 60 insertions(+) create mode 100644 dashboard/src/states/Dashboard/contexts/Project/ProjectContext.jsx create mode 100644 dashboard/src/states/Dashboard/contexts/Project/index.js diff --git a/dashboard/src/states/Dashboard/contexts/Project/ProjectContext.jsx b/dashboard/src/states/Dashboard/contexts/Project/ProjectContext.jsx new file mode 100644 index 0000000..3591651 --- /dev/null +++ b/dashboard/src/states/Dashboard/contexts/Project/ProjectContext.jsx @@ -0,0 +1,59 @@ +import {createContext, useEffect, useState} from "react"; +import {getRequest} from "@/common/utils/RequestUtil.js"; +import Loading from "@/states/Loading"; +import {useNavigate, useParams} from "react-router-dom"; + +export const ProjectContext = createContext({}); + +export const ProjectProvider = ({children}) => { + const [projects, setProjects] = useState(null); + const [currentProject, setCurrentProject] = useState(null); + + const {projectId} = useParams(); + const navigate = useNavigate(); + + const updateProjects = async () => { + try { + const data = await getRequest("/project/list"); + + if (data instanceof Array) { + setProjects(data); + + if (data.length > 0) { + if (projectId) { + const project = data.find((project) => project.id === projectId); + if (!project) { + navigate("/projects/" + data[0].id + "/stats"); + return setCurrentProject(data[0]); + } + setCurrentProject(project); + } else { + setCurrentProject(data[0]); + } + } else { + if (projectId) navigate("/"); + setCurrentProject(null); + } + } + } catch (e) { + console.error(e.message); + } + } + + useEffect(() => { + setTimeout(updateProjects, 1000); + }, []); + + useEffect(() => { + const interval = setInterval(updateProjects, 10000); + return () => clearInterval(interval); + }, [currentProject]); + + if (projects === null) return ; + + return ( + + {children} + + ) +} \ No newline at end of file diff --git a/dashboard/src/states/Dashboard/contexts/Project/index.js b/dashboard/src/states/Dashboard/contexts/Project/index.js new file mode 100644 index 0000000..5b462ed --- /dev/null +++ b/dashboard/src/states/Dashboard/contexts/Project/index.js @@ -0,0 +1 @@ +export * from "./ProjectContext.jsx"; \ No newline at end of file