@apollo/client#QueryHookOptions TypeScript Examples

The following examples show how to use @apollo/client#QueryHookOptions. 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: Apollo.ts    From graphql-ts-client with MIT License 6 votes vote down vote up
export function useTypedQuery<
    TData extends object,
    TVariables extends object
>( 
    fetcher: Fetcher<"Query", TData, TVariables>,
    options?: QueryHookOptions<TData, TVariables> & {
        readonly operationName?: string,
		readonly registerDependencies?: boolean | { readonly fieldDependencies: readonly Fetcher<string, object, object>[] }
	}
) : QueryResult<TData, TVariables> {

    const body = requestBody(fetcher);

	const [operationName, request] = useMemo<[string, DocumentNode]>(() => {
		const operationName = options?.operationName ?? `query_${util.toMd5(body)}`;
		return [operationName, gql`query ${operationName}${body}`];
	}, [body, options?.operationName]);

	const [dependencyManager, config] = useContext(dependencyManagerContext);
	const register = options?.registerDependencies !== undefined ? !!options.registerDependencies : config?.defaultRegisterDependencies ?? false;
	if (register && dependencyManager === undefined) {
		throw new Error("The property 'registerDependencies' of options requires <DependencyManagerProvider/>");
	}
	useEffect(() => {
		if (register) {
			dependencyManager!.register(
				operationName, 
				fetcher, 
				typeof options?.registerDependencies === 'object' ? options?.registerDependencies?.fieldDependencies : undefined
			);
			return () => { dependencyManager!.unregister(operationName); };
		}// eslint-disable-next-line
	}, [register, dependencyManager, operationName, options?.registerDependencies, request]); // Eslint disable is required, becasue 'fetcher' is replaced by 'request' here.
	const response = useQuery<TData, TVariables>(request, options);
	const responseData = response.data;
	const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
	return newResponseData === responseData ? response : { ...response, data: newResponseData };
}
Example #2
Source File: video.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useChannelPreviewVideos = (
  channelId: string | null | undefined,
  opts?: QueryHookOptions<GetVideosQuery>
) => {
  const { data, ...rest } = useGetVideosQuery({
    ...opts,
    variables: {
      where: {
        channel: {
          id_eq: channelId,
        },
        isPublic_eq: true,
        isCensored_eq: false,
        thumbnailPhoto: {
          isAccepted_eq: true,
        },
        media: {
          isAccepted_eq: true,
        },
      },
      orderBy: VideoOrderByInput.CreatedAtDesc,
      offset: 0,
      limit: 10,
    },
    skip: !channelId || opts?.skip,
  })
  return {
    videos: data?.videos,
    ...rest,
  }
}
Example #3
Source File: useActivity.ts    From lexicon with MIT License 6 votes vote down vote up
export function useActivity(
  options?: QueryHookOptions<UserActivityType, UserActivityVariables>,
  errorAlert: ErrorAlertOptionType = 'SHOW_ALERT',
) {
  const { data, loading, error, networkStatus, refetch, fetchMore } = useQuery<
    UserActivityType,
    UserActivityVariables
  >(
    USER_ACTIVITY,
    {
      ...options,
    },
    errorAlert,
  );

  return { data, loading, error, networkStatus, refetch, fetchMore };
}
Example #4
Source File: search.ts    From atlas with GNU General Public License v3.0 6 votes vote down vote up
useSearch = (
  variables: SearchQueryVariables,
  opts?: QueryHookOptions<SearchQuery, SearchQueryVariables>
) => {
  const { data, ...rest } = useSearchQuery({ ...opts, variables })

  return {
    data: data?.search,
    ...rest,
  }
}
Example #5
Source File: Apollo.ts    From graphql-ts-client with MIT License 5 votes vote down vote up
export function useTypedLazyQuery<
    TData extends object,
    TVariables extends object
>( 
    fetcher: Fetcher<"Query", TData, TVariables>,
    options?: QueryHookOptions<TData, TVariables> & {
        readonly operationName?: string,
		readonly registerDependencies?: boolean | { readonly fieldDependencies: readonly Fetcher<string, object, object>[] }
	}
) : QueryTuple<TData, TVariables> {

    const body = requestBody(fetcher);

	const [operationName, request] = useMemo<[string, DocumentNode]>(() => {
		const operationName = options?.operationName ?? `query_${util.toMd5(body)}`;
		return [operationName, gql`query ${operationName}${body}`];
	}, [body, options?.operationName]);

	const [dependencyManager, config] = useContext(dependencyManagerContext);
	const register = options?.registerDependencies !== undefined ? !!options.registerDependencies : config?.defaultRegisterDependencies ?? false;
	if (register && dependencyManager === undefined) {
		throw new Error("The property 'registerDependencies' of options requires <DependencyManagerProvider/>");
	}
	useEffect(() => {
		if (register) {
			dependencyManager!.register(
				operationName, 
				fetcher, 
				typeof options?.registerDependencies === 'object' ? options?.registerDependencies?.fieldDependencies : undefined
			);
			return () => { dependencyManager!.unregister(operationName); };
		}// eslint-disable-next-line
	}, [register, dependencyManager, operationName, options?.registerDependencies, request]); // Eslint disable is required, becasue 'fetcher' is replaced by 'request' here.
	const response = useLazyQuery<TData, TVariables>(request, options);
	const responseData = response[1].data;
	const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
	return newResponseData === responseData ? response : [
        response[0],
        { ...response[1], data: newResponseData }
    ] as QueryTuple<TData, TVariables>;
}
Example #6
Source File: user.pager.query.ts    From ui with GNU Affero General Public License v3.0 5 votes vote down vote up
useUserPagerQuery = (
  options?: QueryHookOptions<Data, Variables>
): QueryResult<Data, Variables> => useQuery<Data, Variables>(QUERY, options)
Example #7
Source File: generate.hooks.ts    From condo with MIT License 4 votes vote down vote up
export function generateReactHooks<GQL, GQLInput, UIForm, UI, Q> (gql, { convertToGQLInput, convertToUIState }: IHookConverters<GQL, GQLInput, UI, UIForm>): IHookResult<UI, UIForm, Q> {

    function useObject (variables: Q, options?: QueryHookOptions<{ objs?: GQL[], meta?: { count?: number } }, Q>) {
        const { loading, refetch, fetchMore, objs, count, error } = useObjects(variables, options)
        if (count && count > 1) throw new Error('Wrong query condition! return more then one result')
        const obj = (objs.length) ? objs[0] : null
        return { loading, refetch, fetchMore, obj, error }
    }
    function useObjects (variables: Q, options?: QueryHookOptions<{ objs?: GQL[], meta?: { count?: number } }, Q>) {
        const intl = useIntl()
        const ServerErrorPleaseTryAgainLaterMsg = intl.formatMessage({ id: 'ServerErrorPleaseTryAgainLater' })
        const AccessErrorMsg = intl.formatMessage({ id: 'AccessError' })

        const result = useQuery<{ objs?: GQL[], meta?: { count?: number } }, Q>(gql.GET_ALL_OBJS_WITH_COUNT_QUERY, {
            variables,
            notifyOnNetworkStatusChange: true,
            ...options,
        })

        let error: ApolloError | string
        if (error && String(error).includes('not have access')) {
            error = AccessErrorMsg
        } else if (error) {
            error = ServerErrorPleaseTryAgainLaterMsg
        }

        const objs: UI[] = getObjects(result.data, convertToUIState)

        const count = (result.data && result.data.meta) ? result.data.meta.count : null

        return {
            loading: result.loading,
            refetch: result.refetch,
            fetchMore: result.fetchMore,
            objs,
            count,
            error,
        }
    }

    /**
     * Client hook that uses create-mutation of current schema
     * @param attrs - values, that will be passed to update input unchanged by form
     */
    function useCreate (attrs: UIForm | Record<string, unknown> = {}, onComplete) {
        if (typeof attrs !== 'object' || !attrs) throw new Error('useCreate(): invalid attrs argument')
        const [rowAction] = useMutation(gql.CREATE_OBJ_MUTATION)
        async function _action (state: UIForm) {
            const { data, errors } = await rowAction({
                variables: { data: convertToGQLInput({ ...state, ...attrs }) },
            })
            if (data && data.obj) {
                const result = convertToUIState(data.obj)
                if (onComplete) onComplete(result)
                return result
            }
            if (errors) {
                console.warn(errors)
                throw errors
            }
            throw new Error('unknown action result')
        }

        return useMemo(() => _action, [rowAction])
    }

    function useUpdate (attrs = {}, onComplete) {
        if (typeof attrs !== 'object' || !attrs) throw new Error('useUpdate(): invalid attrs argument')
        const [rowAction] = useMutation(gql.UPDATE_OBJ_MUTATION)

        async function _action (state, obj) {
            if (!obj || !obj.id) throw new Error('No obj.id argument')
            const { data, errors } = await rowAction({
                variables: {
                    id: obj.id,
                    data: convertToGQLInput({ ...state, ...attrs }, obj),
                },
            })
            if (data && data.obj) {
                const result = convertToUIState(data.obj)
                if (onComplete) onComplete(result)
                return result
            }
            if (errors) {
                console.warn(errors)
                throw errors
            }
            throw new Error('unknown action result')
        }

        return useMemo(() => _action, [rowAction])
    }

    function useDelete (attrs = {}, onComplete) {
        if (typeof attrs !== 'object' || !attrs) throw new Error('useDelete(): invalid attrs argument')
        const [rowAction] = useMutation(gql.DELETE_OBJ_MUTATION)

        async function _action (obj) {
            if (!obj || !obj.id) throw new Error('No obj.id argument')
            const { data, errors } = await rowAction({
                variables: {
                    id: obj.id,
                },
            })
            if (data && data.obj) {
                const result = convertToUIState(data.obj)
                if (onComplete) onComplete(result)
                return result
            }
            if (errors) {
                console.warn(errors)
                throw errors
            }
            throw new Error('unknown action result')
        }

        return useMemo(() => _action, [rowAction])
    }

    function useSoftDelete (attrs = {}, onComplete) {
        if (typeof attrs !== 'object' || !attrs) throw new Error('useSoftDelete(): invalid attrs argument')
        const [rowAction] = useMutation(gql.UPDATE_OBJ_MUTATION)

        async function _action (state, obj) {
            if (!obj.id) throw new Error('No obj.id argument')
            const { data, errors } = await rowAction({
                variables: {
                    id: obj.id,
                    data: convertToGQLInput({ ...state, deletedAt: 'true' }, obj),
                },
            })
            if (data && data.obj) {
                const result = convertToUIState(data.obj)
                if (onComplete) onComplete(result)
                return result
            }
            if (errors) {
                console.warn(errors)
                throw errors
            }
            throw new Error('unknown action result')
        }

        return useMemo(() => _action, [rowAction])
    }
    return {
        gql,
        useObject,
        useObjects,
        useCreate,
        useUpdate,
        useDelete,
        useSoftDelete,
    }
}