UNPKG

@preact-signals/query

Version:

A reactive utility for React/Preact that simplifies the handling of data fetching and state management. Powered by Preact Signals, it provides hooks and functions to create reactive resources and manage their state seamlessly.

55 lines 2.38 kB
"use client"; import * as React from "react"; import { useSignalOfState } from "@preact-signals/utils/hooks"; export const defaultContext = React.createContext(undefined); // export const signalContext = React.createContext< // ReadonlySignal<QueryClient> | undefined // >(undefined); const QueryClientSharingContext = React.createContext(false); // If we are given a context, we will use it. // Otherwise, if contextSharing is on, we share the first and at least one // instance of the context across the window // to ensure that if React Query is used across // different bundles or microfrontends they will // all use the same **instance** of context, regardless // of module scoping. function getQueryClientContext(context, contextSharing) { if (context) { return context; } if (contextSharing && typeof window !== "undefined") { if (!window.ReactQueryClientContext) { window.ReactQueryClientContext = defaultContext; } return window.ReactQueryClientContext; } return defaultContext; } export const useQueryClient = ({ context } = {}) => { const queryClient = React.useContext(getQueryClientContext(context, React.useContext(QueryClientSharingContext))); if (!queryClient) { throw new Error("No QueryClient set, use QueryClientProvider to set one"); } return queryClient; }; export const useQueryClient$ = (options) => useSignalOfState(useQueryClient(options)); export const QueryClientProvider = ({ client, children, context, contextSharing = false, }) => { React.useEffect(() => { client.mount(); return () => { client.unmount(); }; }, [client]); if (process.env.NODE_ENV !== "production" && contextSharing) { client .getLogger() .error(`The contextSharing option has been deprecated and will be removed in the next major version`); } // const $client = useSignalOfState(client); // const $context = useSignalOfState(context); // const $contextSharing = useSignalOfState(contextSharing); const Context = getQueryClientContext(context, contextSharing); return (React.createElement(QueryClientSharingContext.Provider, { value: !context && contextSharing }, React.createElement(Context.Provider, { value: client }, children))); }; //# sourceMappingURL=QueryClientProvider.js.map