Skip to content

Commit

Permalink
Add useInstanceConfig hook
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Danielv123 committed May 18, 2024
1 parent 7489a76 commit e82da23
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion packages/web_ui/src/model/instance.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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;
};

0 comments on commit e82da23

Please sign in to comment.