Add useInstanceConfig hook

Currently the web interface implements configs by pulling the state directly in the components where they are used. I need to access the instance config for a plugin, which would require me to duplicate parts of the instance config retrival code.
Instead, I implement it here under lib. This allows 3rd party consumers to get immediate access if we decide to implement a subscription model for configs in the future.
This commit is contained in:
Danielv123 authored and Daniel committed 2024-05-18 20:57:16 +01:00
1 parent 7489a76d4a
commit 692075df1d
1 file changed
+17 -1
+17 -1
View File
@@ -1,4 +1,6 @@
import { useCallback, useContext, useSyncExternalStore } from "react";
import { useCallback, useContext, useEffect, useState, useSyncExternalStore } from "react";
import { Static } from "@sinclair/typebox";
import { Config, InstanceConfigGetRequest } from "@clusterio/lib";
import ControlContext from "../components/ControlContext";
export function useInstance(id?: number) {
@@ -11,3 +13,17 @@ export function useInstances() {
const subscribe = useCallback((callback: () => void) => control.instances.subscribe(callback), [control]);
return useSyncExternalStore(subscribe, () => control.instances.getSnapshot());
}
export function useInstanceConfig(id?: number) {
let control = useContext(ControlContext);
const [config, setConfig] = useState(undefined as undefined | Static<typeof Config.jsonSchema>);
useEffect(() => {
if (id) {
control.send(new InstanceConfigGetRequest(id))
.then(conf => setConfig(conf));
}
}, [id]);
return config;
};