Computed params with skip/enable

Viewed 245

I was getting annoyed that some of my apollo requests were working and some were not. The ones that don't seem to work are requests with computed params. Here is an example of one that does work:

import { computed } from "@vue/composition-api";

import * as getCategoryBySlug from "@graphql/api/query.category.gql";

import { useGraphQuery } from "./graph-query";

export function useGetCategory(context) {
  const params = computed(() => {
    const slug = context.root.$route.params.categorySlug;
    if (!slug) return;
    return { slug };
  });

  const { response, error, loading } = useGraphQuery(
    params,
    getCategoryBySlug,
    (data) => data.categoryBySlug
  );

  return { category: response, categoryError: error, categoryLoading: loading };
}

As I am computing my params on the categorySlug, it is available on the route, so it should never be null/undefined.

My useGraphQuery method looks like this:

import { useQuery, useResult } from "@vue/apollo-composable";

export function useGraphQuery(params, gql, pathFn, clientId = "apiClient") {
  // if (!params?.value)
  //   return {
  //     response: ref(undefined),
  //     loading: ref(false),
  //     error: ref(undefined),
  //     query: ref(undefined),
  //   };

  // TODO: figure our a way to skip the call if the parameters are null

  const { result, loading, error, query, fetchMore } = useQuery(gql, params, {
    clientId,
    //enabled: !!params?.value,
  });
  const response = useResult(result, null, pathFn);

  return { response, loading, error, query, fetchMore };
}

As you can see, I am having an issue because I can't skip and enabled doesn't seem to work as a suitable workaround (for skip). I tried to return a reference if the parameters are null/undefined, but this never tried to execute the query if the computed params became available. So my question is how can I skip the request or wait until the params are available?

1 Answers

You should consider changing the flow that calls this method, so it would be called only when the params are defined, instead of trying to skip it when not ready and try to retrigger it again from within the method. Most of the time this will make the code clearer, and also make it more resource-efficient as it won't make unneeded method calls.

If you depend on user input try to validate the input is ready before calling this method.

You can also add a watcher on the params that will trigger the flow when they change, and check in the watcher that all the relevant values are defined before calling the method.

Of course, if you can use computed variables it is better than using watchers in most cases, but in some cases, it can help (mostly when the variable is calculated by an async function, for example, the use of apollo request).

Related