Using Apollo Client to make direct server calls - no cache, no hooks

I came across one scenario in my application where I want to use Apollo Client to make a direct server call rather that using the useQuery hook. The scenario is implementing an autocomplete field using React Select. As the user types characters into the text field, the application must send queries to the server to get matching items.

To do this, React Select provides a loadOptions property. It is a callback that gets the user input as an argument and expects a list of matches as the return value. In this scenario, I just need to directly send a graphql query to the server and get a result. There is no need for caching or trying to structure the useQuery hook inside the callback. (Even using refetch seems to be quite awkward.)

const AutocompleteField = () => {
  const loadOptions = (inputValue: string) => {
    ...
  }

  return (
    <AsyncSelect
      value={selectedOption}
      loadOptions={loadOptions}
    />
  );
};

How can I achieve this using Apollo Client? Note that I could use fetch or axios, but would prefer to stick with Apollo Client as the infrastructure is all setup.

Hi! You could use useApolloClient to get an Apollo Client instance, then use client.query to execute the query and pass fetchPolicy: 'network-only' to make sure the response isn’t cached.

4 Likes

This is perfect, @mindnektar. I did not know about client.query, but it worked like a charm. Thank you so much!

Just a small correction - the network-only fetch policy still tries to write to the cache (we know, it’s a misleading name :man_facepalming:). To completely avoid saving to the cache, the no-cache fetch policy is a better fit.

2 Likes