react-query#QueryFunction TypeScript Examples

The following examples show how to use react-query#QueryFunction. 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: useAxiosStrategy.ts    From react-starter-boilerplate with MIT License 5 votes vote down vote up
useAxiosStrategy = (): ApiClientContextValue => {
  const client = useMemo(() => {
    const axios = Axios.create({
      headers: {
        'Content-Type': 'application/json',
      },
      baseURL: `${process.env.REACT_APP_API_URL}`,
    });

    axios.interceptors.request.use(requestSuccessInterceptor);
    axios.interceptors.response.use(responseSuccessInterceptor, responseFailureInterceptor);

    return axios;
  }, []);

  const queryFn = useCallback(
    <TData>(): QueryFunction<TData> =>
      async ({ queryKey: [url] }) => {
        if (typeof url === 'string') {
          const lowerCaseUrl = url.toLowerCase();
          const { data } = await client.get(`/${lowerCaseUrl}`);
          return data;
        }
        throw new Error('Invalid QueryKey');
      },
    [client],
  );

  const infiniteQueryFn = useCallback(
    <TArgs, TParams, TResponse, TError>(
        query: InfiniteQueryFn<TArgs, TParams, TResponse>,
        options?: UseInfiniteQueryOptions<TArgs, TParams, TError, TResponse>,
      ): QueryFunction<TParams> =>
      async ({ pageParam = options?.startPage ?? 0 }) => {
        const { endpoint, args } = query(options?.args);
        const cursorKey = options?.cursorKey;
        // End format of url is e.g /users?page=2&sortOrder=ASC&limit=5&sortBy=name
        const { data } = await client.get(
          `/${endpoint}?${cursorKey}=${pageParam}&${stringify(args, { addQueryPrefix: false })}`,
        );
        return data;
      },
    [client],
  );

  const mutationFn = useCallback(
    <TParams = unknown, TData = unknown>(mutation: MutationFn<TParams, TData>): MutationFunction<TData, TParams> =>
      async (variables) => {
        const { endpoint, params, method } = mutation(variables);

        const axiosConfig: AxiosRequestConfig = {
          url: `/${endpoint}`,
          data: params ? JSON.stringify(params) : undefined,
          method: method || 'POST',
        };
        const { data } = await client.request(axiosConfig);
        return data;
      },
    [client],
  );

  return {
    queryFn,
    infiniteQueryFn,
    mutationFn,
  };
}
Example #3
Source File: useKyStrategy.ts    From react-starter-boilerplate with MIT License 5 votes vote down vote up
useKyStrategy = (): ApiClientContextValue => {
  const client = useMemo(() => {
    return Ky.create({
      headers: {
        'Content-Type': 'application/json',
      },
      prefixUrl: `${process.env.REACT_APP_API_URL}`,
      hooks: {
        beforeRequest: [requestSuccessHook],
        beforeError: [responseErrorHook],
      },
      retry: 1,
    });
  }, []);

  const queryFn = useCallback(
    <TData>(): QueryFunction<TData> =>
      async ({ queryKey: [url] }) => {
        if (typeof url === 'string') {
          const lowerCaseUrl = url.toLowerCase();
          return await client.get(lowerCaseUrl).json<TData>();
        }
        throw new Error('Invalid QueryKey');
      },
    [client],
  );

  const infiniteQueryFn = useCallback(
    <TArgs, TParams, TResponse, TError>(
        _query: InfiniteQueryFn<TArgs, TParams, TResponse>,
        options?: UseInfiniteQueryOptions<TArgs, TParams, TError, TResponse>,
      ): QueryFunction<TParams> =>
      async ({ pageParam = 0 }) => {
        const { endpoint, args } = _query(options?.args);
        const cursorKey = options?.cursorKey;
        // End format of url is e.g /users?page=2&sortOrder=ASC&limit=5&sortBy=name
        return await client
          .get(`${endpoint}?${cursorKey}=${pageParam}&${stringify(args, { addQueryPrefix: false })}`)
          .json<TParams>();
      },
    [client],
  );

  const mutationFn = useCallback(
    <TParams = unknown, TData = unknown>(mutation: MutationFn<TParams, TData>): MutationFunction<TData, TParams> =>
      async (variables) => {
        const { endpoint, params, method } = mutation(variables);

        const kyConfig: Options = {
          json: params ?? undefined,
          method: method || 'POST',
        };

        return await client(endpoint, kyConfig).json<TData>();
      },
    [client],
  );

  return {
    queryFn,
    infiniteQueryFn,
    mutationFn,
  };
}
Example #4
Source File: restRequests.ts    From frontend with MIT License 5 votes vote down vote up
queryFn: QueryFunction = async function ({ queryKey }) {
  const response = await apiClient.get(queryKey.join('/'))
  return await response.data
}
Example #5
Source File: restRequests.ts    From frontend with MIT License 5 votes vote down vote up
queryFnFactory = <T>(config?: AxiosRequestConfig): QueryFunction<T> =>
  async function ({ queryKey }) {
    const response = await apiClient.get<T>(queryKey.join('/'), config)
    return await response.data
  }
Example #6
Source File: restRequests.ts    From frontend with MIT License 5 votes vote down vote up
authQueryFnFactory = <T>(token?: string): QueryFunction<T> => {
  return queryFnFactory<T>(authConfig(token))
}