Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type Fetcher<T> = () => Promise<T>;
- type QueryResult<T> = { data: T };
- interface Query<T> {
- data: T;
- new (key: string, fun: Fetcher<T>): Query<T>;
- invalidate(): void;
- fetch(): Promise<void>;
- }
- interface QueryClient<T> {
- new (cache: QueryCache): QueryClient<T>;
- fetch(key: string, fun: Fetcher<T>): Promise<QueryResult<T>>;
- invalidateQuery(key: string): void;
- createResult(query: Query<T>): QueryResult<T>;
- }
- interface QueryCache {
- set(key: string, value: any): void;
- createQuery(key: string, fun: Fetcher<any>): Query<any>;
- findQuery(key: string): Query<any> | null;
- }
- type ZalupaData = { data: number };
- class Api {
- async fetchZalupa(id: number): Promise<ZalupaData> {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- return { data: 10 };
- }
- }
- class Zalupa {
- data: ZalupaData | null = null;
- constructor(
- private api: Api,
- private client: QueryClient<ZalupaData | null>
- ) {}
- async fetchZalupa(id: number) {
- let result;
- try {
- const response = await this.api.fetchZalupa(id);
- result = response;
- } catch (e) {
- console.log(e);
- }
- return result || null;
- }
- async getZalupa(id: number) {
- const fun = () => this.api.fetchZalupa(id);
- const { data } = await this.client.fetch(this.getKey(id), fun);
- if (data) {
- this.setData(data);
- }
- }
- invalidate(id: number) {
- this.client.invalidateQuery(this.getKey(id));
- }
- private getKey(id: number) {
- return `zalupa-${id}`;
- }
- private setData(data: ZalupaData) {
- this.data = data;
- }
- }
- function useZalupa() {
- const cache = useMemo(() => new QueryCache(), []);
- const client = useMemo(() => new QueryClient(cache), []);
- const api = useMemo(() => new Api(), []);
- return useMemo(() => new Zalupa(client, api), [client]);
- }
- function Component({ id }: { id: number }) {
- const zalupa = useZalupa();
- useOnEvent("EVENT", ({ id }) => {
- zalupa.invalidateQuery(id);
- zalupa.getZalupa(id);
- });
- useEffect(() => {
- zalupa.getZalupa(id);
- }, [id]);
- return <>{zalupa.data}</>;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement