Skip to content

Instantly share code, notes, and snippets.

@IlCallo
Created March 31, 2023 16:08
Show Gist options
  • Save IlCallo/193c3c6ba2777e3b86db629f165a42e5 to your computer and use it in GitHub Desktop.
Save IlCallo/193c3c6ba2777e3b86db629f165a42e5 to your computer and use it in GitHub Desktop.
Helpers to use together with @vue/apollo-composable
import { gql } from "@apollo/client/core";
import { useQuery } from "@vue/apollo-composable";
import { computed, ComputedRef, Ref } from "vue";
export interface ApolloResult<Model> {
// This key is usually the name of the query
[key: string]: Model | undefined;
}
type ApolloResultRef<Model> = Ref<ApolloResult<Model> | undefined>;
// Inspired by deprecated useResult from vue-apollo
export function useFirstResult<Model>(
result: ApolloResultRef<Model>,
defaultValue: Model
): ComputedRef<Model>;
export function useFirstResult<Model>(
result: ApolloResultRef<Model>
): ComputedRef<Model | undefined>;
export function useFirstResult<Model>(
result: ApolloResultRef<Model>,
defaultValue?: Model
) {
return computed(
() => result.value?.[Object.keys(result.value)[0]] ?? defaultValue
);
}
export const GET_NAMES_QUERY = gql`
query getNames() {
getNames
}
`;
const { result, loading } = useQuery<ApolloResult<string[]>>(GET_NAMES_QUERY);
const names = useFirstResult(result, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment