Apolloclient.query example

Apolloclient.query example DEFAULT

Best JavaScript code snippets using apollo-client.ApolloClient.query(Showing top 15 results out of 315)

try { const health = ( await apolloClient.query({ query: gql` query Health { cache: new InMemoryCache(), }); const healthResponse = await apolloClient.query({ query: gql` query Health { }; const health = ( await apolloClient.query({ query: gql` query Health {
const { data } = await client.query({ query: SEARCH_USERS, variables: { searchQuery: debounceSearchQuery },
const getProducts = () =>{ return client.query({ fetchPolicy: 'network-only', query: gql` { products{id, name} } ` }) }
const getOwners = searchText => async (dispatch) => { dispatch(loadingOwners()); client .query({ query: ownersQuery, variables: { searchText } }) .then(({ error, data }) => { if (error) { thrownew Error(error); } return dispatch(showOwners(ownersFromData(data))); }) .catch(error => dispatch(showOwnersError(error))); }
function getJobs() { returnnew Promise((resolve, reject) => { client .query({ query: JOBS_QUERY }) .then(resolve) .catch(reject); }); }
client.query({ query: gql` { users { id displayName } } ` }) .then(result => console.log(result));
client .query({ query: postsQuery }) .then(data => { const { posts } = data.data; this.setState({ posts }); }) .catch(err => { console.log("catch", err); });
asyncfunction getRoutes () { const output = ['/', '/about', '/books'] const { data } = await client.query({ query: gql` query graphql { books { id } } ` }) return output.concat(data.books.map(book => `/books/${encodeURIComponent(book.id)}`)) }
const getServerSideProps = async (context) => { let {query: { slug }} = context const id = slug ? slug : context.query.id; const result = await client.query({ query: PRODUCT_BY_SLUG_QUERY, variables: { id } }) return { props: { product: result.data.product, revalidate: 1, }, }; }
async fetchGraphQlData() { const { data } = awaitthis.client.query({ query: GET_ALL }); / console.log('data ', data); this.setState({messageTest: data.a1}) }
function* handleQuery<T>(options: WatchQueryOptions) { const client: ApolloClient = yield getClient(); const response: ApolloQueryResult<T> = yield call(client.query, options); returnyield response.data; }
const getRepositories = ownerLogin => async (dispatch) => { dispatch(loadingRepositories()); client .query({ query: repositoriesQuery, variables: { ownerLogin } }) .then(({ error, data }) => { if (error) { thrownew Error(error); } return dispatch(showRepositories(repositoriesFromData(data))); }) .catch(error => dispatch(showRepositoriesError(error))); }
const queryWithApolloConsumer = () => ( <ApolloConsumer> {client => { client .query({ query: gql` { chatroom(id:1) { id title } } ` }) .then(result => console.log(result)); returnnull; }} </ApolloConsumer> )
async getSharedInboxEndpoints() { const result = awaitthis.client.query({ query: gql` query { SharedInboxEndpoint { uri } } `, }) throwErrorIfApolloErrorOccurred(result) return result.data.SharedInboxEnpoint }
const { data } = await client.query({ query: SEARCH_USERS, variables: { searchQuery: debounceSearchQuery },
Sours: https://www.tabnine.com/code/javascript/functions/apollo-client/ApolloClient/query

Time to accomplish: 10 minutes

Now that we've set up Apollo Client, we can integrate it into our React app. This lets us use React Hooks to bind the results of GraphQL queries directly to our UI.

If you're starting the tutorial here, first clone the example app.

Integrate with React

To connect Apollo Client to React, we wrap our app in the component from the package. We pass our client instance to the component via the prop.

The code blocks below use TypeScript by default. You can use the dropdown menu above each code block to switch to JavaScript.

If you're using JavaScript, use and file extensions wherever and appear.

Open and replace its contents with the following:


The component is similar to React’s context provider: it wraps your React app and places on the context, which enables you to access it from anywhere in your component tree.

Now we're ready to build React components that execute GraphQL queries.

Display a list of launches

Let's build the page in our app that shows a list of available SpaceX launches. Open . Right now, the file looks like this:


Define the query

First, we'll define the shape of the query we'll use to fetch a paginated list of launches. Paste the following below the declaration of :


Using fragments

Notice that our query definition pulls in the definition above it. defines a GraphQL fragment, which is named . A fragment is useful for defining a set of fields that you can include across multiple queries without rewriting them.

In the query above, we include the fragment in our query by preceding it with , similar to JavaScript spread syntax.

Notice that in addition to fetching a list of , our query fetches and fields. That's because the query returns paginated results:

  • The field indicates whether there are additional launches beyond the list returned by the server.
  • The field indicates the client's current position within the list of launches. We can execute the query again and provide our most recent as the value of the variable to fetch the next set of launches in the list.

Apply the hook

We'll use Apollo Client's React Hook to execute our new query within the component. The hook's result object provides properties that help us populate and render our component throughout the query's execution.

  1. Modify your import to include , and import a few predefined components for rendering the page:


    If you're using TypeScript, also import the necessary types that are generated from your server's schema definitions:


  2. Replace the dummy declaration of with the following:


This component passes our query to and obtains , , and properties from the result. Depending on the state of those properties, we render a list of launches, a loading indicator, or an error message.

Start up both your server and client with and visit . If everything's configured correctly, our app's main page appears and lists 20 SpaceX launches!

We have a problem though: there are more than 20 SpaceX launches in total. Our server paginates its results and includes a maximum of 20 launches in a single response.

To be able to fetch and store all launches, we need to modify our code to use the and fields included in our query. Let's learn how.

Apollo Client 3 provides new pagination helper functions for offset-based and Relay-style pagination that are not yet reflected in this tutorial.

Apollo Client provides a helper function to assist with paginated queries. It enables you to execute the same query with different values for variables (such as the current cursor).

Add to the list of objects we destructure from the result object, and also define an state variable:


Now we can connect to a button within the component that fetches additional launches when it's clicked.

Paste this code directly above the closing tag in the component:


When our new button is clicked, it calls (passing the current as the value of the variable) and displays a Loading notice until the query returns results.

Let's test our button. Start everything up and visit again. A Load More button now appears below our 20 launches. Click it. After the query returns, no additional launches appear. 🤔

If you check your browser's network activity, you'll see that the button did in fact send a followup query to the server, and the server did in fact respond with a list of launches. However, Apollo Client keeps these lists separate, because they represent the results of queries with different variable values (in this case, the value of ).

We need Apollo Client to instead merge the launches from our query with the launches from our original query. Let's configure that behavior.

Merge cached results

Apollo Client stores your query results in its in-memory cache. The cache handles most operations intelligently and efficiently, but it doesn't automatically know that we want to merge our two distinct lists of launches. To fix this, we'll define a function for the paginated field in our schema.

Open , where our default is initialized:


The schema field that our server paginates is the list of . Modify the initialization of to add a function for the field, like so:


This function takes our cached launches and the launches and combines them into a single list, which it then returns. The cache stores this combined list and returns it to all queries that use the field.

This example demonstrates a use of field policies, which are cache configuration options that are specific to individual fields in your schema.

If you try clicking the Load More button now, the UI will successfully append additional launches to the list!

Display a single launch's details

We want to be able to click a launch in our list to view its full details. Open and replace its contents with the following:


This query includes all the details we need for the page. Notice that we're reusing the fragment that's already defined in .

Once again, we'll pass our query to the hook. This time, we also need to pass the corresponding launch's to the query as a variable. The value of is available as a prop that's passed by the router.

Now replace the contents of with the following:


Just like before, we use the status of the query to render either a or state, or data when the query completes.

Return to your app and click a launch in the list to view its details page.

Display the profile page

We want a user's profile page to display a list of launches that they've booked a seat on. Open and replace its contents with the following:


You should recognize all of the concepts in this code from the pages we've already completed, with one highlighted exception: we're setting a .

Customizing the fetch policy

As mentioned earlier, Apollo Client stores query results in its cache. If you query for data that's already present in your cache, Apollo Client can return that data without needing to fetch it over the network.

However, cached data can become stale. Slightly stale data is acceptable in many cases, but we definitely want our user's list of booked trips to be up to date. To handle this, we've specified a fetch policy for our query.

A fetch policy defines how Apollo Client uses the cache for a particular query. The default policy is , which means Apollo Client checks the cache to see if the result is present before making a network request. If the result is present, no network request occurs.

By setting this query's fetch policy to , we guarantee that Apollo Client always queries our server to fetch the user's most up-to-date list of booked trips.

For a list of all supported fetch policies, see Supported fetch policies.

If you visit the profile page in your app, you'll notice that the query returns null. This is because we still need to implement login functionality. We'll tackle that in the next section!

Edit on GitHub

Sours: https://www.apollographql.com/docs/tutorial/queries/
  1. Bbq grills kmart
  2. Circleci vs teamcity
  3. Paper clipart
  4. Mac art library palette looks
  5. Fight club poster

This article shows how to fetch GraphQL data in React with the hook and attach the result to your UI. You'll also learn how Apollo Client simplifies data management code by tracking error and loading states for you.


This article assumes you're familiar with building basic GraphQL queries. If you need a refresher, we recommend this guide. You can also build example queries against Apollo's full-stack tutorial server.

This article also assumes that you've already set up Apollo Client and have wrapped your React app in an component. For more information, see the getting started guide.

To follow along with the examples below, open up our starter project and sample GraphQL server on CodeSandbox. You can view the completed version of the app here.

Executing a query

The React hook is the primary API for executing queries in an Apollo application. To run a query within a React component, call and pass it a GraphQL query string. When your component renders, returns an object from Apollo Client that contains , , and properties you can use to render your UI.

Let's look at an example. First, we'll create a GraphQL query named . Remember to wrap query strings in the function to parse them into query documents:


Next, we'll create a component named . Inside it, we'll pass our query to the hook:


As our query executes and the values of , , and change, the component can intelligently render different UI elements according to the query's state:

  • As long as is (indicating the query is still in flight), the component presents a notice.
  • When loading is and there is no , the query has completed. The component renders a dropdown menu that's populated with the list of dog breeds returned by the server.

When the user selects a dog breed from the populated dropdown, the selection is sent to the parent component via the provided function.

In the next step, we'll associate the dropdown with a more sophisticated query that uses GraphQL variables.

Caching query results

Whenever Apollo Client fetches query results from your server, it automatically caches those results locally. This makes subsequent executions of the same query extremely fast.

To see this caching in action, let's build a new component called . accepts a prop called that reflects the current value of the dropdown menu in our component:


Notice that we're providing a configuration option () to the hook this time. The option is an object that contains all of the variables we want to pass to our GraphQL query. In this case, we want to pass the currently selected from the dropdown.

Select from the dropdown to see its photo appear. Then switch to another breed, and then switch back to . You'll notice that the bulldog photo loads instantly the second time around. This is the Apollo cache at work!

Next, let's learn some techniques for ensuring that our cached data is fresh.

Updating cached query results

Sometimes, you want to make sure that your query's cached data is up to date with your server's data. Apollo Client supports two strategies for this: polling and refetching.


Polling provides near-real-time synchronization with your server by executing your query periodically at a specified interval. To enable polling for a query, pass a configuration option to the hook with an interval in milliseconds:


By setting to 500, we fetch the current breed's image from the server every 0.5 seconds. Note that if you set to , the query does not poll.

You can also start and stop polling dynamically with the and functions that are returned by the hook.


Refetching enables you to refresh query results in response to a particular user action, as opposed to using a fixed interval.

Let's add a button to our component that calls our query's function whenever it's clicked.

You can optionally provide a new object to the function. If you don't (as is the case in the following example), the query uses the same variables that it used in its previous execution.


Click the button and notice that the UI updates with a new dog photo. Refetching is an excellent way to guarantee fresh data, but it introduces some complexity with loading state. In the next section, we'll cover strategies for handling complex loading and error state.

Providing new variables to

You call with a new set of variables like so:

If you provide new values for some of your original query's variables but not all of them, uses each omitted variable's original value.

Inspecting loading states

We've already seen that the hook exposes our query's current loading state. This is helpful when a query first loads, but what happens to our loading state when we're refetching or polling?

Let's return to our refetching example from the previous section. If you click the refetch button, you'll see that the component doesn't re-render until the new data arrives. What if we want to indicate to the user that we're refetching the photo?

The hook's result object provides fine-grained information about the status of the query via the property. To take advantage of this information, we set the option to so our query component re-renders while a refetch is in flight:


Enabling this option also ensures that the value of updates accordingly, even if you don't want to use the more fine-grained information provided by the property.

The property is a enum that represents different loading states. Refetch is represented by , and there are also values for polling and pagination. For a full list of all the possible loading states, check out the source.

To view a complete version of the app we just built, check out the CodeSandbox here.

Inspecting error states

You can customize your query error handling by providing the configuration option to the hook. The default value is , which tells Apollo Client to treat all GraphQL errors as runtime errors. In this case, Apollo Client discards any query response data returned by the server and sets the property in the result object to .

If you set to , does not discard query response data, allowing you to render partial results.

For more information, see Handling operation errors.

Manual execution with

When React renders a component that calls , Apollo Client automatically executes the corresponding query. But what if you want to execute a query in response to a different event, such as a user clicking a button?

The hook is perfect for executing queries in response to events besides component rendering. Unlike with , when you call , it does not immediately execute its associated query. Instead, it returns a query function in its result tuple that you call whenever you're ready to execute the query.

Here's an example:


The first item in 's return tuple is the query function, and the second item is the same result object returned by .

As shown above, you can pass options to the query function just like you pass them to itself. If you pass a particular option to both, the value you pass to the query function takes precedence. This is a handy way to pass default options to and then customize those options in the query function.

For a full list of supported options, see the API reference.

Setting a fetch policy

By default, the hook checks the Apollo Client cache to see if all the data you requested is already available locally. If all data is available locally, returns that data and doesn't query your GraphQL server. This policy is Apollo Client's default fetch policy.

You can specify a different fetch policy for a given query. To do so, include the option in your call to :

You can also specify a query's . If you do, is used for the query's first execution, and is used to determine how the query responds to future cache updates:

For example, this is helpful if you want a query to always make an initial network request, but you're comfortable reading from the cache after that.

Supported fetch policies


Apollo Client first executes the query against the cache. If all requested data is present in the cache, that data is returned. Otherwise, Apollo Client executes the query against your GraphQL server and returns that data after caching it.

Prioritizes minimizing the number of network requests sent by your application.

This is the default fetch policy.

Apollo Client executes the query only against the cache. It never queries your server in this case.

A query throws an error if the cache does not contain data for all requested fields.

Apollo Client executes the full query against both the cache and your GraphQL server. The query automatically updates if the result of the server-side query modifies cached fields.

Provides a fast response while also helping to keep cached data consistent with server data.

Apollo Client executes the full query against your GraphQL server, without first checking the cache. The query's result is stored in the cache.

Prioritizes consistency with server data, but can't provide a near-instantaneous response when cached data is available.

Similar to , except the query's result is not stored in the cache.

Uses the same logic as , except this query does not automatically update when underlying field values change. You can still manually update this query with and .


Supported options and result fields for the hook are listed below.

Most calls to can omit the majority of these options, but it's useful to know they exist. To learn about the hook API in more detail with usage examples, see the API reference.


The hook accepts the following options:

Name /

Operation options

A GraphQL query string parsed into an AST with the template literal.

Optional for the hook, because the query can be provided as the first parameter to the hook. Required for the component.

An object containing all of the GraphQL variables your query requires to execute.

Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.

Specifies how the query handles a response that returns both GraphQL errors and partial results.

For details, see GraphQL error policies.

The default value is , meaning that the query result includes error details but not partial results.

A callback function that's called when your query successfully completes with zero errors (or if is and partial data is returned).

This function is passed the query's result .

A callback function that's called when the query encounters one or more errors (unless is ).

This function is passed an object that contains either a object or a array, depending on the error(s) that occurred.

If , the query is not executed. Not available with .

This property is part of Apollo Client's React integration, and it is not available in the core API.

The default value is .

The name of your component to be displayed in the React Developer Tools.

The default value is .

Networking options

Specifies the interval (in milliseconds) at which the query polls for updated results.

The default value is (no polling).

If , the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.

The default value is .

If you're using Apollo Link, this object is the initial value of the object that's passed along your link chain.

Pass to skip executing the query during server-side rendering.

The instance of to use to execute the query.

By default, the instance that's passed down via context is used, but you can provide a different instance here.

Caching options

Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy.

The default value is .

Specifies the to use for all executions of this query after this execution.

For example, you can use this to switch back to a fetch policy after using or for a single execution.

If , the query can return partial results from the cache if the cache doesn't contain results for all queried fields.

The default value is .

Deprecated options

Deprecated. If , causes a query if the query result is detected as partial. Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

The default value is .


After being called, the hook returns a result object with the following properties. This object contains your query result, plus some helpful functions for refetching, dynamic polling, and pagination.

Name /

Operation data

An object containing the result of your GraphQL query after it completes.

This value might be if a query results in one or more errors (depending on the query's ).

An object containing the result from the most recent previous execution of this query.

This value is if this is the query's first execution.

If the query produces one or more errors, this object contains either an array of or a single . Otherwise, this value is .

For more information, see Handling operation errors.

An object containing the variables that were provided for the query.

Network info

If , the query is still in flight and results have not yet been returned.

A number indicating the current network state of the query's associated request. See possible values.

Used in conjunction with the option.

The instance of Apollo Client that executed the query.

Can be useful for manually executing followup queries or writing data to the cache.

If , the associated lazy query has been executed.

This field is only present on the result object returned by .

Helper functions

A function that enables you to re-execute the query, optionally passing in new .

To guarantee that the refetch performs a network request, its is set to (unless the original query's is or , which also guarantee a network request).

See also Refetching.

A function that helps you fetch the next set of results for a paginated list field.

A function that instructs the query to begin re-executing at a specified interval (in milliseconds).

A function that instructs the query to stop polling after a previous call to .

A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.

This function returns another function that you can call to terminate the subscription.

A function that enables you to update the query's cached result without executing a followup GraphQL operation.

Next steps

Now that you understand how to fetch data with the hook, learn how to update your data with the hook!

After that, learn about some other handy Apollo Client features:

Edit on GitHub

Sours: https://www.apollographql.com/docs/react/data/queries/
GraphQL Tutorial - Full Guide To Making Queries (2018)

apollographql / react-apollo Public archive

Intended outcome:

To receive query results from the network when the cache does not contain the stored data.

constclient=newApolloClient({// By default, this client will send queries to the// `/graphql` endpoint on the same hostlink: concat(authMiddleware,httpLink),cache: newInMemoryCache(),defaultOptions: {query: {fetchPolicy: 'cache-and-network'}}})client.query({query: gql` { users() { id full_name email } }`}).then(r=>{console.info(r)// {data: {}, loading: false, networkStatus: 7, stale: false}})

Actual outcome:

Instead of receiving data from the network null is returned. I am assuming this is because the data has yet to be stored in the cache. Using behaves as expected but always returns no data.

client.query({query: gql` { users() { id full_name email } }`}).then(r=>{console.info(r)// {data: null, loading: true, networkStatus: 1, stale: true}})

How to reproduce the issue:

Set the fetchPolicy to and try to load data via the function.


Sours: https://github.com/apollographql/react-apollo/issues/1386

Example apolloclient.query


#4 The Query Component - Level 1 Apollo Client with React


You will also like:


626 627 628 629 630