Skip to content

Commit

Permalink
feat(hooks): add useCrestronSubscribeDigital
Browse files Browse the repository at this point in the history
  • Loading branch information
damienbutt committed Apr 13, 2022
1 parent fff51f4 commit f0f7dce
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useCrestronSubscribeDigital";
35 changes: 35 additions & 0 deletions src/hooks/useCrestronSubscribeDigital/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useState, useRef, useEffect } from "react";
import { subscribeState, unsubscribeState } from "@crestron/ch5-crcomlib";
import CrestronCH5 from "@norgate-av/crestron-ch5-helper";

export function useCrestronSubscribeDigital(
signalName: string,
callback?: (value: boolean) => void,
): [boolean] {
const [state, setState] = useState<boolean>(false);
const callbackRef = useRef<(value: boolean) => void | undefined>();

useEffect(() => {
callbackRef.current = callback;
}, [callback]);

useEffect(() => {
const signalType = CrestronCH5.SignalType.Boolean;
const id = subscribeState(signalType, signalName, (value: boolean) => {
setState(value);

if (callbackRef.current) {
callbackRef.current(value);
}
});

return () => {
unsubscribeState(signalType, signalName, id);
};
}, [signalName]);

return [state];
}

export default useCrestronSubscribeDigital;
export const useCrestronSubscribeBoolean = useCrestronSubscribeDigital;
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export {};
export * from "./hooks";

0 comments on commit f0f7dce

Please sign in to comment.