This commit is contained in:
ari committed 2022-07-28 21:50:23 -04:00
1 parent 2a827c24f6
commit 57c86093a4
29 files changed
+145 -1901

No files matched your search

+58 -55
View File
@@ -1,59 +1,62 @@
import { Collection, Connection } from "home-assistant-js-websocket";
import { useState, useEffect } from 'react';
import { useState, useEffect } from "react";
import { useHAConnection } from "./connection";
type _HACollectionState<T> = {
ready: false,
collection?: Collection<T>,
} | {
ready: true,
collection: Collection<T>,
}
export type HACollectionState<T, D = {}> = _HACollectionState<T> & {
additional: Partial<D>
}
export const useHassCollection = <T, D extends {} = {}>(
getHACollection: (c: Connection) => Collection<T>,
updateAdditionalProps?: (n: T | {}) => D,
): HACollectionState<T, D> => {
const [state, setState] = useState<_HACollectionState<T>>({
ready: false
});
const conn = useHAConnection();
useEffect(() => {
if (conn.status === 'loaded' && !state.ready) {
const collection = getHACollection(conn.connection);
setState({
ready: false,
collection,
})
const unsub = collection.subscribe(d => {
if (d && !state.ready) {
setState({
ready: true,
collection,
})
unsub();
} else if (!d && state.ready) {
setState({
ready: true,
collection,
})
unsub();
}
});
return unsub
}
}, [conn, getHACollection, state.ready]);
return {
...state,
get additional(): Partial<D> {
if (state.ready && updateAdditionalProps) {
return updateAdditionalProps(state.collection.state)
}
return {}
}
type _HACollectionState<T> =
| {
ready: false;
collection?: Collection<T>;
}
}
| {
ready: true;
collection: Collection<T>;
};
export type HACollectionState<T, D = {}> = _HACollectionState<T> & {
additional: Partial<D>;
};
export const useHassCollection = <T, D extends {} = {}>(
getHACollection: (c: Connection) => Collection<T>,
updateAdditionalProps?: (n: T | {}) => D
): HACollectionState<T, D> => {
const [state, setState] = useState<_HACollectionState<T>>({
ready: false,
});
const conn = useHAConnection();
useEffect(() => {
if (conn.status === "loaded" && !state.ready) {
const collection = getHACollection(conn.connection);
setState({
ready: false,
collection,
});
const unsub = collection.subscribe((d) => {
console.log("updating collection", d);
if (d && !state.ready) {
setState({
ready: true,
collection,
});
// unsub();
} else if (!d && state.ready) {
setState({
ready: true,
collection,
});
// unsub();
}
});
return unsub;
}
}, [conn, getHACollection, state.ready]);
return {
...state,
get additional(): Partial<D> {
if (state.ready && updateAdditionalProps) {
return updateAdditionalProps(state.collection.state);
}
return {};
},
};
};