import * as React from "react";
import { FEAGlobals } from "../../common/Globals";
const { useState, useEffect } = React;
/**
 * A generic effect for getting and setting state dynamically from a Router pubsub channel.
 *
 * @param {string} topic The pubsub topic (i.e. channel) to subscribe
 * @param {object} initialMessage The initial state (defaults to empty object)
 * @returns [object, function] The current state of the pubsub channel (or initialMessage if no state exists).
 * The second returned array parameter is a publish function which can be used to update state.
 *
 * @example
 * // Inside a React functional component
 * const [currentState, publish] = usePubSub("topic", {});
 * console.log(currentState);
 *
 * onClick = () => {
 *    publish(someNewState);
 * }
 */
function usePubSub(topic, initialMessage = {}) {
    const [message, setMessage] = useState(initialMessage);
    const pub = (value) => FEAGlobals.FSBL.Clients.RouterClient.publish(topic, value);
    useEffect(() => {
        const subscribeId = FEAGlobals.FSBL.Clients.RouterClient.subscribe(topic, (err, res) => {
            if (err) {
                // Use Finsemble Logger?
                console.error(err);
            }
            setMessage(res.data);
        });
        return () => {
            FEAGlobals.FSBL.Clients.RouterClient.unsubscribe(subscribeId);
        };
    }, []);
    return [message, pub];
}
export { usePubSub };
//# sourceMappingURL=usePubSub.js.map