waku-react/src/useFilterSubscribe.ts
Sasha 4b219df40c
feat!: add basic @waku/react hooks (#1)
* add react and typecript
* add react, rollup and ts
* add waku dependencies
* add create hooks, providers and update typings path
* extend create hooks and provider with error/loading state
* rename to isLoading
* create useContentPair hook
* add protocols property and bootstrap with remote peers
* add useFilterSubscribe
* add eslint & fix issues
* add prettier & fix
* add jest
* add husky
* add bundlewatch
2023-02-16 21:49:46 +01:00

59 lines
1.4 KiB
TypeScript

import { useCallback, useEffect, useState } from "react";
import type { IDecodedMessage, IDecoder, Waku } from "@waku/interfaces";
import type { HookState } from "./types";
type UseFilterSubscribeParams = {
waku: Waku;
decoder: IDecoder<IDecodedMessage>;
};
type UseFilterSubscribeResult = HookState & {
messages: IDecodedMessage[];
};
export const useFilterSubscribe = (
params: UseFilterSubscribeParams,
): UseFilterSubscribeResult => {
const { waku, decoder } = params;
const [error, setError] = useState<null | string>(null);
const [isLoading, setLoading] = useState<boolean>(false);
const [messages, setMessage] = useState<IDecodedMessage[]>([]);
const pushMessage = useCallback(
(message: IDecodedMessage): void => {
setMessage((prev) => [...prev, message]);
},
[setMessage],
);
useEffect(() => {
let unsubscribe: null | (() => Promise<void>) = null;
setLoading(true);
waku?.filter
?.subscribe([decoder], pushMessage)
.then((unsubscribeFn) => {
setLoading(false);
unsubscribe = unsubscribeFn;
})
.catch((err) => {
setLoading(false);
setError(
`Failed to subscribe to filer: ${err?.message || "no message"}`,
);
});
return () => {
unsubscribe?.();
};
}, [waku, decoder, pushMessage, setError, setLoading]);
return {
error,
messages,
isLoading,
};
};