react-apollo-hooks icon indicating copy to clipboard operation
react-apollo-hooks copied to clipboard

Typescript complains that data prop in query hook can be undefined

Open sami616 opened this issue 6 years ago • 3 comments

This makes destructuring the data prop very hard.

  const {
    data: { todos }, // because data prop doesn't fallback to an empty object this destructuring fails  
    loading,
    error,
  } = useQuery<Todos.Data>(TODOS)

Would be very helpful if this was an empty object by default like documented in the apollo docs:

`data`: TData
An object containing the result of your GraphQL query. Defaults to an empty object.

sami616 avatar Apr 08 '19 07:04 sami616

I'm having the same issue. An empty object would indeed be nicer.

warreee avatar Apr 10 '19 13:04 warreee

data is undefined when skip option is equal to true. It's similar how react-apollo works: https://github.com/apollographql/react-apollo/blob/da452d117bdad8da6a87ada23c793b2eeb0fea7c/src/Query.tsx#L64.

trojanowski avatar May 02 '19 14:05 trojanowski

@trojanowski thanks for the reply, indeed it seems to be the same. However, I haven't found out why react-apollo returns at least an empty object and this library returns either TData or undefined: const queryResult = useQuery<TData, TVariables>(query); Any idea?

I fixed temporarily by re-exporting the hook and slightly modifying it:

import {
    ApolloCurrentResult,
    ApolloQueryResult,
    FetchMoreOptions,
    FetchMoreQueryOptions,
    NetworkStatus,
    ObservableQuery
} from "apollo-client";
import { DocumentNode } from "apollo-link";
import { useQuery } from "react-apollo-hooks";

export interface QueryHookState<TData>
    extends Pick<
            ApolloCurrentResult<undefined | TData>,
            "error" | "errors" | "loading" | "partial"
        > {
    data: Partial<TData>;
    networkStatus: NetworkStatus | undefined;
}

export interface QueryHookResult<TData, TVariables>
    extends QueryHookState<TData>,
        Pick<
            ObservableQuery<TData, TVariables>,
            "refetch" | "startPolling" | "stopPolling" | "updateQuery"
        > {
    fetchMore<K extends keyof TVariables>(
        fetchMoreOptions: FetchMoreQueryOptions<TVariables, K> &
            FetchMoreOptions<TData, TVariables>
    ): Promise<ApolloQueryResult<TData>>;
}

export const useQueryData = <TData, TVariables = any>(
    query: DocumentNode
): QueryHookResult<TData, TVariables> => {
    const queryResult = useQuery<TData, TVariables>(query);
    const { data } = queryResult;
    if (!data) {
        return {
            ...queryResult,
            data: {}
        };
    } else {
        return {
            ...queryResult,
            data
        };
    }
};

warreee avatar May 15 '19 10:05 warreee