Skip to content

Instantly share code, notes, and snippets.

@kn0ll
Last active December 21, 2019 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kn0ll/902c7ca929dbc2aadc9487aa86fc02a4 to your computer and use it in GitHub Desktop.
Save kn0ll/902c7ca929dbc2aadc9487aa86fc02a4 to your computer and use it in GitHub Desktop.
home assistant react hooks
import constate from "constate";
import * as React from "react";
import {
Connection,
subscribeEntities,
HassEntities,
AuthData,
Auth,
createConnection
} from "home-assistant-js-websocket";
interface AppState {
connection: Connection | undefined;
entities: HassEntities | undefined;
}
export const [HASSProvider, useHass, useHassEntities] = constate(
({ authData }: { authData: AuthData }): AppState => {
const auth = React.useMemo(() => new Auth(authData), [authData]);
const [state, setState] = React.useState<AppState>({
connection: undefined,
entities: undefined
});
const setConnection = (connection: Connection): void =>
setState({ ...state, connection });
const setEntities = (entities: HassEntities): void =>
setState({ ...state, entities });
React.useEffect(() => {
(async (): Promise<void> => {
try {
const connection = await createConnection({ auth });
subscribeEntities(connection, setEntities);
setConnection(connection);
} catch (e) {
console.log("unhandled exception connecting to hass", e);
}
})();
}, []);
return state;
},
value => value,
value => value.entities
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment