A local-first personal finance app
import { useEffect, useState } from 'react';
import type { DependencyList } from 'react';
import type { Query } from '@actual-app/core/shared/query';
import { liveQuery } from '#queries/liveQuery';
import type { LiveQuery } from '#queries/liveQuery';
type UseQueryResult<Response> = {
data: null | ReadonlyArray<Response>;
isLoading: boolean;
error?: Error;
};
export function useQuery<Response = unknown>(
makeQuery: () => Query | null,
dependencies: DependencyList,
): UseQueryResult<Response> {
// Memo the resulting query. We don't care if the function
// that creates the query changes, only the resulting query.
const [memoizedQuery, setMemoizedQuery] = useState(() => ({
dependencies,
query: makeQuery(),
}));
let query = memoizedQuery.query;
if (!areDependenciesEqual(memoizedQuery.dependencies, dependencies)) {
query = makeQuery();
setMemoizedQuery({ dependencies, query });
}
const [data, setData] = useState<ReadonlyArray<Response> | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | undefined>(undefined);
useEffect(() => {
setError(query === null ? new Error('Query is null') : undefined);
setIsLoading(!!query);
if (!query) {
return;
}
let isUnmounted = false;
let live: null | LiveQuery<Response> = liveQuery<Response>(query, {
onData: data => {
if (!isUnmounted) {
setData(data);
setIsLoading(false);
}
},
onError: setError,
});
return () => {
isUnmounted = true;
live?.unsubscribe();
live = null;
};
}, [query]);
return {
data,
isLoading,
...(error && { error }),
};
}
function areDependenciesEqual(a: DependencyList, b: DependencyList) {
return (
a.length === b.length &&
a.every((value, index) => Object.is(value, b[index]))
);
}