feat: treeshakable #12718
Closedmanudeli(GitHub profile, opens in a new tab)wants to merge 32 commits into
query-v6 fromrefs/pull/12718/headopened View on GitHubPushed2b5f3de
Pushedbca3a45
Pushed79a27d1
- @@ -0,0 +67,21 @@67+ * ```ts68+ * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) =>69+ * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts)70+ * ```71+ */72+export function setQueriesData<73+ TQueryFnData,74+ TQueryFilters extends QueryFilters<any> = QueryFilters,75+>(76+ client: QueryClient,77+ filters: TQueryFilters,78+ updater: Updater<79+ NoInfer<TQueryFnData> | undefined,80+ NoInfer<TQueryFnData> | undefined81+ >,82+ options?: SetDataOptions,83+): Array<[QueryKey, TQueryFnData | undefined]> {84+ return notifyManager.batch(() =>85+ findCachedQueries(getQueryCache(client), filters).map(({ queryKey }) => [86+ queryKey,87+ setQueryData<TQueryFnData>(client, queryKey, updater, options),@@ -0,0 +205,21 @@205+ * ```ts206+ * await invalidateQueries(queryClient, { queryKey: ['posts'], refetchType: 'active' })207+ * ```208+ */209+export function invalidateQueries<TTaggedQueryKey extends QueryKey = QueryKey>(210+ client: QueryClient,211+ filters?: InvalidateQueryFilters<TTaggedQueryKey>,212+ options?: InvalidateOptions,213+): Promise<void> {214+ return notifyManager.batch(() => {215+ findCachedQueries(getQueryCache(client), filters).forEach((query) => {216+ invalidateCachedQuery(query)217+ })218+219+ if (filters?.refetchType === 'none') {220+ return Promise.resolve()221+ }222+ return refetchQueries(223+ client,224+ {225+ ...filters,@@ -0,0 +28,21 @@28+ TData,29+ TQueryData,30+ TQueryKey extends QueryKey,31+>(32+ client: QueryClient,33+ observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,34+ options: NoInfer<35+ ObserverOptionsInput<TQueryFnData, TError, TData, TQueryData, TQueryKey>36+ >,37+): Promise<QueryObserverResult<TData, TError>> {38+ const defaultedOptions = defaultQueryOptions(client, options)39+40+ const cache = getQueryCache(client)41+ const query = cache.build(client, defaultedOptions)42+43+ const cached = Promise.withResolvers<QueryObserverResult<TData, TError>>()44+ const unsubscribe = cache.subscribe((event) => {45+ if (46+ event.type === 'updated' &&47+ event.query.queryHash === query.queryHash &&48+ query.state.data !== undefined@@ -0,0 +407,21 @@407+ fetchStatus: 'idle',408+ // Like above, if the query was pending at the moment of dehydration but has data,409+ // we can assume it should be hydrated as successful.410+ status:411+ state.status === 'pending' && data !== undefined412+ ? 'success'413+ : state.status,414+ ...(state.status === 'pending' &&415+ data !== undefined && {416+ dataUpdatedAt: dehydratedAt,417+ }),418+ },419+ )420+ }421+422+ if (423+ promise &&424+ // If the data was synchronously available, there is no need to set up425+ // a retryer and thus no reason to call fetch426+ !syncData &&427+ !existingQueryIsPending &&@@ -0,0 +332,21 @@332+ data,333+ null,334+ variables,335+ this.state.context,336+ mutationFnContext,337+ )338+339+ this.#dispatch({ type: 'success', data })340+ return data341+ } catch (error) {342+ try {343+ // Notify cache callback344+ await this.#mutationCache.config.onError?.(345+ error as any,346+ variables,347+ this.state.context,348+ this as Mutation<unknown, unknown, unknown, unknown>,349+ mutationFnContext,350+ )351+ } catch (e) {352+ void Promise.reject(e)@@ -0,0 +380,21 @@380+ try {381+ await this.options.onSettled?.(382+ undefined,383+ error as TError,384+ variables,385+ this.state.context,386+ mutationFnContext,387+ )388+ } catch (e) {389+ void Promise.reject(e)390+ }391+392+ this.#dispatch({ type: 'error', error: error as TError })393+ throw error394+ } finally {395+ // The settled retryer's promise would otherwise pin this mutation's396+ // result, variables and context for as long as the cache keeps it397+ if (this.#retryer === retryer) {398+ this.#retryer = undefined399+ }400+ this.#mutationCache.runNext(this)@@ -0,0 +219,21 @@219+ */220+ runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {221+ return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve()222+ }223+224+ /**225+ * Removes all mutations and clears their garbage collection timers.226+ * Mutations that are already running continue to execute.227+ * @example228+ * ```ts229+ * const mutationCache = getMutationCache(queryClient)230+ *231+ * mutationCache.clear()232+ * ```233+ */234+ clear(): void {235+ notifyManager.batch(() => {236+ const mutations = this.getAll()237+ this.#mutations.clear()238+ mutations.forEach((mutation) => {239+ mutation.options.scope?.remove(this, mutation)@@ -0,0 +217,21 @@217+ * @example218+ * ```ts219+ * await observer.mutate(220+ * { title: 'New post' },221+ * { onSuccess: (data) => console.log(data) },222+ * )223+ * ```224+ */225+ mutate(226+ variables: TVariables,227+ options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,228+ ): Promise<TData> {229+ this.#mutateOptions = options230+231+ this.#currentMutation?.removeObserver(this)232+233+ this.#currentMutation = Mutation.build(this.#client, this.options)234+235+ this.#currentMutation.addObserver(this)236+237+ return this.#currentMutation.execute(variables)@@ -0,0 +11,21 @@11+ * By default, the `onlineManager` assumes an active network connection, and12+ * listens to the `online` and `offline` events on the `window` object to13+ * detect changes.14+ */15+export class OnlineManager extends Subscribable<Listener> {16+ #online = true17+ #cleanup?: () => void18+19+ #setup: SetupFn20+21+ constructor() {22+ super()23+ this.#setup = (onOnline) => {24+ // addEventListener does not exist in React Native, but window does25+ // oxlint-disable-next-line typescript/no-unnecessary-condition26+ if (typeof window !== 'undefined' && window.addEventListener) {27+ const onlineListener = () => onOnline(true)28+ const offlineListener = () => onOnline(false)29+ // Listen to online30+ window.addEventListener('online', onlineListener, false)31+ window.addEventListener('offline', offlineListener, false)@@ -0,0 +368,21 @@368+ let result = this.#currentResult369+370+ const getSnapshot = () => {371+ const query = getQueryCache(this.#client).build(372+ this.#client,373+ readerOptions,374+ )375+ readerOptions.select?.[0].reuse(376+ readerOptions,377+ query,378+ this.#resultContext,379+ context,380+ )381+382+ const nextResult = this.createResult(383+ query,384+ readerOptions,385+ context,386+ result,387+ )388+ if (!shallowEqualObjects(nextResult, result)) {@@ -0,0 +215,21 @@215+ // Do nothing if already resolved216+ if (isResolved()) {217+ return218+ }219+220+ let promiseOrValue: any221+222+ // we can re-use config.initialPromise on the first call of run()223+ const initialPromise =224+ failureCount === 0 ? config.initialPromise : undefined225+226+ // Execute query227+ try {228+ promiseOrValue = initialPromise ?? config.fn()229+ } catch (error) {230+ promiseOrValue = Promise.reject(error)231+ }232+233+ Promise.resolve(promiseOrValue)234+ .then(resolve)235+ .catch((error) => {@@ -0,0 +81,21 @@81+>({82+ streamFn,83+ refetchMode = 'reset',84+ reducer = (items, chunk) =>85+ [...(items as Array<TQueryFnData>), chunk] as TData,86+ initialValue = [] as TData,87+}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<88+ TData,89+ TQueryKey90+> {91+ return async (context) => {92+ const signalContext: FetchSignalContext = context93+ const signal = signalContext[fetchSignal]94+ if (signal?.aborted) {95+ return initialValue96+ }97+98+ const query = findCachedQuery(getQueryCache(context.client), {99+ queryKey: context.queryKey,100+ exact: true,101+ })@@ -0,0 +97,21 @@97+ // Hydrate existing queries after commit so an aborted transition cannot update them.98+ const hydrationQueue: DehydratedState['queries'] | undefined =99+ React.useMemo(() => {100+ const queryCache = getQueryCache(client)101+102+ const newQueries: DehydratedState['queries'] = []103+ const existingQueries: DehydratedState['queries'] = []104+ for (const dehydratedQuery of state.queries) {105+ const existingQuery = queryCache.get(dehydratedQuery.queryHash)106+107+ if (!existingQuery) {108+ newQueries.push(dehydratedQuery)109+ continue110+ }111+112+ const hydrationIsNewer =113+ dehydratedQuery.state.dataUpdatedAt >114+ existingQuery.state.dataUpdatedAt ||115+ (dehydratedQuery.promise &&116+ existingQuery.state.status !== 'pending' &&117+ existingQuery.state.fetchStatus !== 'fetching' &&@@ -0,0 +107,21 @@107+ if (!existingQuery) {108+ newQueries.push(dehydratedQuery)109+ continue110+ }111+112+ const hydrationIsNewer =113+ dehydratedQuery.state.dataUpdatedAt >114+ existingQuery.state.dataUpdatedAt ||115+ (dehydratedQuery.promise &&116+ existingQuery.state.status !== 'pending' &&117+ existingQuery.state.fetchStatus !== 'fetching' &&118+ dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt)119+120+ if (hydrationIsNewer) {121+ existingQueries.push(dehydratedQuery)122+ }123+ }124+125+ if (newQueries.length > 0) {126+ // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo127+ hydrateQueries(client, newQueries, optionsRef.current)@@ -0,0 +127,21 @@127+ *128+ * return (129+ * <div>130+ * {status === 'error' ? <span>Error: {error.message}</span> : null}131+ * <ul>132+ * {data.map((post) => <li key={post.id}>{post.title}</li>)}133+ * </ul>134+ * </div>135+ * )136+ * }137+ * ```138+ */139+ <140+ TQueryFnData = unknown,141+ TError = DefaultError,142+ TData = TQueryFnData,143+ TQueryKey extends QueryKey = QueryKey,144+ >(145+ options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &146+ TPolicy,147+ ): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &@@ -0,0 +29,21 @@29+}30+31+/**32+ * Attaches the selected observer and its Suspense policy in one copy.33+ * @param options - The fetcher and options supplied by the caller.34+ * @param Observer - The observer selected by the public factory.35+ * @returns A descriptor that uses the ordinary render policy for a skipped fetcher.36+ */37+export function prepareSuspenseOptions<38+ TOptions extends { queryFn?: unknown },39+ TObserver,40+>(41+ options: TOptions,42+ Observer: TObserver,43+): TOptions & QueryDescriptor<TObserver> & SuspenseQueryMode<true> {44+ const enabled = options.queryFn !== skipToken45+ return {46+ ...options,47+ [observerKey]: Observer,48+ enabled,49+ throwOnError: [throwOnError, defaultThrowOnError],
Pushed176571a
Pushed4fe5467
Pushed156e2a3
manudeli(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Review comments that did not fit the review summary for
79a27d19(part 1/1)