Apollo fetchpolicy

Apollo fetchpolicy DEFAULT

Apollo client fetchPolicy issues - query called twice

I'm using @apollo/client 3.2.0 with react. I have a component that retrieves the data using the useQuery hook. The query looks similar to this one:

As you can see in the query, I have two variables: year and type. Both are passed as props in the component and this component is rendered twice in the same view, with a different type prop.

The problem that I have is related to the fetchPolicy option. If I'm using one of or fetch policies, one of the queries is called twice. This doesn't happen when I use . So I think it's a cache conflict, because the queries are similar, but I'm not sure and I don't know how to fix this.

Do you have any ideas?

asked Dec 9 '20 at 11:14

AlinAlin

32033 silver badges1515 bronze badges

Sours: https://stackoverflow.com/questions/65215697/apollo-client-fetchpolicy-issues-query-called-twice

# Queries

Fetching data involves executing query operations using standard GraphQL documents. You can learn more about queries and GraphQL documents here(opens new window) and practice running queries in the playground(opens new window).

# Executing a query

# GraphQL document

Let's take this example GraphQL document throughout this section:

TIP

It is recommended to give a name to your GraphQL operations (here ), so it is easier to find them in the Apollo Client devtools.

This query would return a object with an array of with their , , and . It could look like this:

You may ask: why is there a nested property on ? Why isn't the array directly on ?

This is because you can select multiple root fields in a GraphQL operation:

In this case, the result could look like this:

There can also be other optional properties on the result alongside :

  • : an array of errors returned by the server
  • : additional informations such as execution timings

# useQuery

The main composition function used to execute queries is . In your component, start by importing it:

You can use in your option and pass it a GraphQL document as the first parameter. Then retrieve the query :

Note that here is a holding the data from the result returned by Apollo.

If you want to directly access the data object, use :

In this example, you could also watch the directly:

Let's expose our result in the template:

Beware that may not contain your data at all time! It will initially be until the query successfully completes. So it's a good idea to add a conditional before rendering the data:

# Query status

# Loading state

Alongside , returns , a boolean tracking the loading state of the query:

# Error

There is also an that holds any error that may occur during the request:

# useResult

The sister composition function is available alongside to facilitate usage of the query .

# Result picking

The first useful feature of is picking one object from the result data. To do so, pass the data as the first parameter, and a picking function as the third parameter:

This is very useful if the data relevant to your component is nested in the query:

Another perk of is that the picking function will silence errors inside the picking function. For example, if is , you don't have to add additional checks:

TIP

Don't forget that can still be until the query successfully completes!

Another use case where proves to be very useful is when you have multiple objects on the result data:

Look how we cleanly separated the result data into two different !

# Automatic picking

If there is only one object in the data, will automatically try to pick the object:

Here will be the array retrieved from our server.

# Default value

Let's say we want to sort our users on their last names:

Here we will run into an error because can be (and potentially can also be ). So the method will throw an error when called in our property.

We could add checks, but it can rapidly become tedious:

We can further simplify this with :

But we can eliminate the conditional entirely if we pass a default value as the 2nd parameter of :

This is even more useful if we want to use the array in multiple places in our function!

# Variables

You can pass a object to the 2nd parameter of :

# Variables Ref

You can change them later by retrieving their :

TIP

This will re-fetch the query each time a property from the object changes.

Alternatively, you can pass a directly:

# Reactive object

You can also pass a reactive object:

This also means you can pass from directly, since is already a reactive object:

But beware if you add new props that aren't used in the GraphQL document, you will run into GraphQL validation errors!

# Variables function

Finally, you can pass variables as a function returning an object:

This variables function will be made reactive automatically, so whenever changes, the object of the query will be updated.

This syntax is also useful if you want to use some s in the :

# Options

The third parameter of is an options object, used to configure your query.

Like , you can pass a , a reactive object or a function that will automatically be reactive.

Using a :

Using a reactive object:

Using a function that will automatically be reactive:

See the API Reference for all the possible options.

# Disable a query

You can disable and re-enable a query with the option:

# Fetch Policy

The option allows you to customize how the query will use the Apollo Client cache.

Available values are:

  • (default): return result from cache. Only fetch from network if cached result is not available.
  • : return result from cache first (if it exists), then return network result once it's available.
  • : return result from cache if available, fail otherwise.
  • : return result from network, fail if network call doesn't succeed, save to cache.
  • : return result from network, fail if network call doesn't succeed, don't save to cache.

# Updating cached results

When a query is completed, it will update the cache with the result data (depending on the fetch policy). This improves performance the next time the data needs to be rendered in your application and ensures that all components relying on a piece of data is always consistent.

However, you sometimes want to make sure that this data is up-to-date compared to the server.

# Polling

Polling means repeatedly calling the server to automatically update the query data.

You can enable polling with the which will be the interval in ms between each requests repeatedly made to the server.

In this example, we will poll the server every second:

# Refetching

The other way is manually executing the query again in response to an event, as opposed to using a fixed interval.

This is done using the function:

# Event hooks

returns event hooks allowing you to execute code when a specific event occurs.

# onResult

This is called whenever a new result is available.

You can pass the option to force the query to trigger a new result when the network status or error is updated:

# onError

It is triggered when an error occurs:

You can use the function from the package to format the error in the browser console:

Example error:

Error log screenshot

If you are using Webpack or Vue CLI, it's a good idea to only use it in development:

That way it will be dropped when compiling the project for production.

Edit this page(opens new window)

Last Updated:9/20/2021, 5:28:43 PM

← Setup Mutations →

Sours: https://v4.apollo.vuejs.org/guide-composable/query.html
  1. Fort scott dealerships
  2. Mulan vinyl record
  3. Jiji music box
  4. Maxn stock
  5. Dollar tree moose

Damir's Corner.

Default Apollo fetch policy in Nuxt

July 9th 2021 GraphQLNuxtJS

By default, the Apollo GraphQL client caches query responses. When using SSR with data sources that change frequently, this can be a problem. Fortunately, caching can be disabled, but setting this as the default behavior in a NuxtJS application proved more difficult than one would expect.

I used the NuxtJS Apollo module. Setting a different for a single query worked as expected:

However, setting the default value globally in had no effect:

Further investigation revealed two reasons for this.

  1. The default options were not applied in versions prior to 4.0.1-rc.4.

  2. I had to use query instead of as the key inside to make it work, although the documentation states otherwise:

The second part is even more intriguing. When I created a sample project for this blogpost, it turned out that the documented key works fine with smart queries:

But when I explicitly called the Apollo client methods, the key was ignored and I had to use instead:

To make matters worse, the key in the caused the smart queries to fail:

Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag?

This could be a problem if you use both smart queries and explicit method calls in your project. Fortunately, this is not the case for me.

You can try the described behavior in a sample project from my GitHub repository. Since I'm using the GitHub GraphQL API, you'll need to create your own personal access token and put it in for the application to work.

The default query options in the NuxtJS Apollo module only work since version , but even in the most recent version (), the correct key to use depends on how you run the queries. For smart queries, use . For explicit calls to Apollo client methods, use instead. Unfortunately, the presence of this key in the default options causes smart queries to fail.

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.

If you need a team of experienced software engineers to help you with a project, contact us at Razum.

Share on Social Media

Copyright
Creative Commons License
Sours: https://www.damirscorner.com/blog/posts/20210709-DefaultApolloFetchPolicyInNuxt.html
GraphQL With React Tutorial - Apollo Client

A real hussar must have a bunch of offspring. The captain was able to make an heir, but such a gallant military lieutenant colonel cannot - but it's just apolitical, as our unforgettable Leonid Ilyich often expressed. Well, and you, dear Nadia, I also urgently ask you personally, personally and in full measure to ensure that Aristov tried his best.

To fulfill my most important assignment.

Fetchpolicy apollo

The man nodded towards the casino. The Tuscan tried to determine from his gaze what kind of woman he was talking. About. Three women were in his field of vision. Expensive outfits, diamonds in the ears and on the neck, glasses of champagne and boredom in every movement.

Type Policies in Apollo Client 3: An Introduction

I have always been a girl, even though I was born a boy, the chick said with a certain note of pride in her voice, flapping her eyelashes. How. - Vadim widened his eyes, which caused a lively girlish laugh. After a pause, looking at the deserted courtyard through the window. Vadim continued interrogation on topics of interest to him: Ours, - again, proudly straightening her shoulders, said the beauty, exposing small mounds for review.

Similar news:

Having moistened the penis well, Eugene sank onto the penis for the second time and drove it almost halfway into his ass. The feeling was that the whole ass was already full, and it was about to break, but at the same time it was nice to feel such a powerful unit in him.

It did not work out completely, and therefore Eugene again got down and began It was Saturday. May. Hot.



18143 18144 18145 18146 18147