// This Source Code Form is subject to the terms of the Mozilla Public
// License, v2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import { useCallback, useEffect, useState } from "react";
import { useAppConfiguration, } from "@foxglove/studio-base/context/AppConfigurationContext";
/**
 * Load a value from app configuration and provide a function to change it
 * This function behaves similarly to useState for a given app configuration key.
 */
export function useAppConfigurationValue(key) {
    const appConfiguration = useAppConfiguration();
    const [configurationValue, setConfigurationValue] = useState(() => {
        const val = appConfiguration.get(key);
        // coerce empty strings into undefined
        if (typeof val === "string" && val.length === 0) {
            return undefined;
        }
        return val;
    });
    useEffect(() => {
        const handler = (val) => {
            setConfigurationValue(val);
        };
        appConfiguration.addChangeListener(key, handler);
        return () => {
            appConfiguration.removeChangeListener(key, handler);
        };
    }, [key, appConfiguration]);
    const wrappedSetter = useCallback(async (value) => {
        setConfigurationValue(value);
        await appConfiguration.set(key, value);
    }, [appConfiguration, key]);
    return [configurationValue, wrappedSetter];
}
//# sourceMappingURL=useAppConfigurationValue.js.map