reactjsapollo-clientreact-apollographql-jsreact-apollo-hooks

Apollo Client useQuery react hook for GET requests


The API resource I am trying to pull from expects a GET request. How can I use the useQuery hook to send a GET request, it seems like it only ever sends POST requests.

In my limited understanding of GraphQL, should the server be changed so the endpoint for GET_ALL_MODELS is a POST request or do I need to change something on the frontend so my Query sends a GET method request.


Solution

  • There are 2 ways to implement this.

    One is setting up your ApolloClient to send all queries as GET. This is achieved using HttpLink with useGETForQueries as true

    import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from '@apollo/client';
    
    const client = new ApolloClient({
      cache: new InMemoryCache(),
      link: new HttpLink({
        uri: '/graphql',
        useGETForQueries: true
      }),
    });
    

    And in case you need to do it for a specific query, you could override the ApolloLink context and set fetchOptions.method to GET.

    const query = useQuery(gql`...`, {variables: {...}, context: {fetchOptions: {method: 'GET'}}})