react-query#QueryKey TypeScript Examples

The following examples show how to use react-query#QueryKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useAnchorQuery.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
useAnchorQuery = <
  TQueryFnData = unknown,
  TError = unknown,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
>(
  queryKey: TQueryKey,
  queryFn: QueryFunction<TQueryFnData, TQueryKey>,
  options?: Omit<
    UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
    'queryKey' | 'queryFn'
  >,
): UseQueryResult<TData, TError> => {
  const { queryErrorReporter } = useApp();

  return useQuery(queryKey, queryFn, {
    onError: queryErrorReporter,
    ...options,
  });
}
Example #2
Source File: useInfiniteQuery.ts    From react-starter-boilerplate with MIT License 6 votes vote down vote up
useInfiniteQuery = <TArgs = unknown, TParams = unknown, TError = unknown, TResponse = TParams>(
  queryKey: QueryKey,
  query: InfiniteQueryFn<TArgs, TParams, TResponse>,
  options?: UseInfiniteQueryOptions<TArgs, TParams, TError, TResponse>,
): UseInfiniteQueryResult<TResponse, TError> => {
  const { infiniteQueryFn } = useApiClient();
  const _infiniteQueryFn = useMemo(
    () => infiniteQueryFn<TArgs, TParams, TResponse, TError>(query, options),
    [infiniteQueryFn, query, options],
  );

  return useRQInfiniteQuery<TParams, TError, TResponse, QueryKey>(queryKey, _infiniteQueryFn, options);
}
Example #3
Source File: useResource.ts    From ke with MIT License 6 votes vote down vote up
useResource = <ResourceData>(
  userConfigOrKey: ResourceOptionsOrKey<QueryResourceOptions<ResourceData>>,
  requestOptions: QueryOptions<ResourceData> = {}
): ResourceQueryResult<ResourceData> => {
  const userConfig = useConfigResolver(userConfigOrKey)
  const { key, ...options } = userConfig
  const {
    fetchResource: { fn },
  } = useDefaultResourceConfig<ResourceData>()

  const { requestConfig = {}, overrideGlobalOnError, ...queryOptions } = deepmerge(options, requestOptions)

  const queryClient = useQueryClient()
  const globalOnError = queryClient.getDefaultOptions()?.queries?.onError

  if (!!queryOptions.onError && globalOnError && !overrideGlobalOnError) {
    queryOptions.onError = injectInCallback(queryOptions.onError, globalOnError)
  }

  return useQuery(
    [key, requestConfig.lookupField, requestConfig.params] as QueryKey,
    () => fn(key, requestConfig),
    queryOptions
  )
}
Example #4
Source File: useBackgroundPaginatedRequest.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
useBackgroundPaginatedRequest = <T extends InfiniteData<unknown>>(
  queryKey: QueryKey,
): T => {
  const client = useQueryClient();
  const data = client.getQueryData<T>(queryKey);
  useBackgroundRequest(queryKey, {
    callback: ({ res, req }) => {
      if (!res) {
        return;
      }

      const current = client.getQueryData(queryKey) as T;
      const updated = { ...current } as T;
      const index = updated.pages.length - 1;
      updated.pageParams[index] = req.variables.after;
      updated.pages[index] = res;
      client.setQueryData(queryKey, updated);
    },
  });

  return data;
}
Example #5
Source File: useBackgroundRequest.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
useBackgroundRequest = (
  queryKey: QueryKey,
  { callback, enabled = true }: UseBackgroundRequestOptionalProps = {},
): void => {
  const client = useQueryClient();
  useRawBackgroundRequest(({ key, ...args }) => {
    if (!enabled || !isQueryKeySame(key, queryKey)) {
      return;
    }

    if (callback) {
      callback({ key, ...args });
    } else {
      client.setQueryData(queryKey, args.res);
    }
  });
}
Example #6
Source File: PostOptionsReadingHistoryMenu.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
updateReadingHistoryPost =
  (
    queryClient: QueryClient,
    historyQueryKey: QueryKey,
    readHistoryPostUpdated: Partial<ReadHistoryPost>,
    { page, edge }: QueryIndexes,
  ): ((args: { id: string }) => Promise<() => void>) =>
  async () => {
    const oldReadingHistory =
      queryClient.getQueryData<ReadHistoryInfiniteData>(historyQueryKey);
    const newItems = [...oldReadingHistory.pages];
    const history = newItems[page].readHistory.edges[edge].node.post;
    newItems[page].readHistory.edges[edge].node.post = {
      ...history,
      ...readHistoryPostUpdated,
    };
    queryClient.setQueryData<ReadHistoryInfiniteData>(historyQueryKey, {
      ...oldReadingHistory,
      pages: newItems,
    });
    return () => {
      queryClient.setQueryData<ReadHistoryInfiniteData>(
        historyQueryKey,
        oldReadingHistory,
      );
    };
  }
Example #7
Source File: PostActions.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
updatePost =
  (
    queryClient: QueryClient,
    postQueryKey: QueryKey,
    update: (oldPost: PostData) => Partial<Post>,
  ): (() => Promise<() => void>) =>
  async () => {
    await queryClient.cancelQueries(postQueryKey);
    const oldPost = queryClient.getQueryData<PostData>(postQueryKey);
    queryClient.setQueryData<PostData>(postQueryKey, {
      post: {
        ...oldPost.post,
        ...update(oldPost),
      },
    });
    return () => {
      queryClient.setQueryData<PostData>(postQueryKey, oldPost);
    };
  }
Example #8
Source File: PostActions.tsx    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
onUpvoteMutation = (
  queryClient: QueryClient,
  postQueryKey: QueryKey,
  upvoted: boolean,
): (() => Promise<() => void>) =>
  updatePost(queryClient, postQueryKey, (oldPost) => ({
    upvoted,
    numUpvotes: oldPost.post.numUpvotes + (upvoted ? 1 : -1),
  }))
Example #9
Source File: common.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
isQueryKeySame = (left: QueryKey, right: QueryKey): boolean => {
  if (typeof left !== typeof right) {
    return false;
  }

  if (typeof left === 'string' && typeof right === 'string') {
    return left === right;
  }

  if (Array.isArray(left) && Array.isArray(right)) {
    if (left.length !== right.length) {
      return false;
    }

    return left.every((key, i) => key === right[i]);
  }

  return false;
}
Example #10
Source File: useReadingHistory.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
function useReadingHistory(key: QueryKey): UseReadingHistoryReturn {
  const client = useQueryClient();
  const { mutateAsync: hideReadHistory } = useMutation<
    unknown,
    unknown,
    HideReadHistoryProps,
    () => void
  >(
    ({ postId, timestamp }: HideReadHistoryProps) =>
      request(`${apiUrl}/graphql`, HIDE_READING_HISTORY_MUTATION, {
        postId,
        timestamp,
      }),
    {
      onMutate: ({ page, edge }: HideReadHistoryProps & QueryIndexes) => {
        const current = client.getQueryData<ReadHistoryInfiniteData>(key);
        const [history] = current.pages[page].readHistory.edges.splice(edge, 1);
        client.setQueryData(key, (result: ReadHistoryInfiniteData) => ({
          pages: current.pages,
          pageParams: result.pageParams,
        }));

        return () =>
          client.setQueryData(key, (result: ReadHistoryInfiniteData) => {
            result.pages[page].readHistory.edges.push(history);
            return {
              pages: result.pages,
              pageParams: result.pageParams,
            };
          });
      },
      onError: (_, __, rollback) => rollback(),
    },
  );

  return { hideReadHistory };
}
Example #11
Source File: useQuery.ts    From react-starter-boilerplate with MIT License 5 votes vote down vote up
useQuery = <TData = unknown, TError = unknown>(
  queryKey: QueryKey,
  options?: UseQueryOptions<TData, TError>,
): UseQueryResult<TData, TError> => {
  const { queryFn } = useApiClient();
  const _queryFn = useMemo(() => queryFn<TData>(), [queryFn]);
  return useRqQuery<TData, TError, TData, QueryKey>(queryKey, _queryFn, options);
}
Example #12
Source File: PostActions.tsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
onBookmarkMutation = (
  queryClient: QueryClient,
  postQueryKey: QueryKey,
  bookmarked: boolean,
): (() => Promise<() => void>) =>
  updatePost(queryClient, postQueryKey, () => ({
    bookmarked,
  }))