Last active
December 21, 2019 10:27
-
-
Save kn0ll/902c7ca929dbc2aadc9487aa86fc02a4 to your computer and use it in GitHub Desktop.
home assistant react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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