简体   繁体   中英

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.

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'}}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM