1import React, {useState, createContext, useEffect, useContext} from "react";
2import {baseRequest} from "@/common/utils/RequestUtil";
3import {ConfigContext} from "@/common/contexts/Config";
4
5export const NodeContext = createContext({});
6
7export const NodeProvider = (props) => {
8
9 const [config] = useContext(ConfigContext);
10 const [nodes, setNodes] = useState([]);
11 const [currentNode, setCurrentNode] = useState(parseInt(localStorage.getItem("currentNode")) || 0);
12
13 const updateNodes = async () => baseRequest("/nodes").then(async nodes => {
14 if (nodes.ok) setNodes(await nodes.json());
15 });
16
17 useEffect(() => {
18 if (Object.keys(config).length === 0) return;
19 if (!config.viewMode) updateNodes();
20 }, [config]);
21
22 const updateCurrentNode = (node) => {
23 localStorage.setItem("currentNode", node);
24 setCurrentNode(parseInt(node));
25 }
26
27 const findNode = (nodeId) => nodes?.find(node => node.id === nodeId);
28
29 return (
30 <NodeContext.Provider value={[nodes, updateNodes, currentNode, updateCurrentNode, findNode]}>
31 {props.children}
32 </NodeContext.Provider>
33 )
34}