Using alternate variables in the watchQuery() function in Apollo Angular will generate the cached data

Currently, I am implementing a feature in my project that allows users to access and analyze data based on various parameters such as year, location, and gender.

Below is the code snippet that I have developed for this feature:

 this._querySubscription = this._apollo.watchQuery({                      
      query: *insert specific GraphQL query here*,
      variables: {
        // here we define the necessary variables for the query 
      }
    })   
    .valueChanges        
    .subscribe(( { data, loading } ) => { 
      perform actions with the retrieved data                            
    })    

No need to fret about any errors related to function implementation as everything has been carefully set up. In fact, I also have additional code to manage cache handling and eviction.

let cache = this._apollo.client.cache as InMemoryCache
      
        let data = this._apollo.client.cache.readQuery({
          query: *specific GraphQL query*,
          variables: { *using the same variables as defined above*}  
        })
        
        cache.evict({
          fieldName: "*field name from the query*", 
          broadcast: false,
        }); 
        
        this._apollo.client.cache
        .writeQuery({
          query: *specific GraphQL query matching previous*,
          data,
          variables: {
            *reuse same variables*      
          }  
        })

Throughout the process, I have encountered some key observations:

  1. Re-running the watchQuery without utilizing readQuery or writeQuery will result in fetching the same cached data even when different variables are provided.
  2. On the other hand, employing readQuery, writeQuery, and evict before executing a new query with altered variables prevents retrieving the same data from the cache. However, attempting to re-run the initial query afterwards may lead to an empty dataset due to potential modifications made to the cache.
  3. If considering the use of fetchPolicy, experimenting with all available options like cache-first and network-only revealed satisfactory outcomes with cache-network-only. Nevertheless, ensuring completion of request and cache updates before UI modification remains a challenge.

Answer №1

After facing a similar problem, I managed to find a solution by utilizing the

this._querySubscription.refetch(newVariables)
function. This method eliminated the need for manual cache deletion and made the process much smoother.

Answer №2

Dealing with the same issue while using Apollo, I found a solution by creating a dedicated module to manage all GraphQL operations with a Factory and implementing a no-cache approach on the .watchQuery method. It's possible to modify the fetchPolicy setting to allow one of these values:

'cache-first' | 'network-only' | 'cache-only' | 'no-cache' | 'standby' | 'cache-and-network'
(Taken from watchQueryOptions.d.ts).

I'm currently utilizing the most recent versions of the following packages:

"@apollo/client": "^3.2.4",
"apollo-angular": "^2.0.4",
"graphql": "^15.3.0",

Below is the module setup:

import { NgModule } from '@angular/core';
import { InMemoryCache } from '@apollo/client/core';
import { Apollo, APOLLO_OPTIONS } from 'apollo-angular';

import { HttpLink } from 'apollo-angular/http';

export function createApollo(httpLink: HttpLink) {
    return {
        link: httpLink.create({
            uri: "/api/...",
            withCredentials: true
        }),
        cache: new InMemoryCache(),
        credentials: 'include',
    };
}

@NgModule({
    exports: [],
    providers: [
        {
            provide: APOLLO_OPTIONS,
            useFactory: createApollo,
            deps: [HttpLink],
        },
    ],
})

export class GraphQLModule {
    constructor(
        apollo: Apollo,
        httpLink: HttpLink
    ) {
        apollo.create({
            link: httpLink.create({
                uri: "/api/...",
                withCredentials: true
            }),
            cache: new InMemoryCache()
        }, "network");
    }
}

Edit the tsconfig.json file with the necessary versions by adding this line:

"allowSyntheticDefaultImports": true
under compilerOptions

To execute the query in a component:

this.apollo
    .watchQuery({
        query: your_query,
            variables: {
                ...your_variables
            },
            returnPartialData: false,
            fetchPolicy: "no-cache" // <----- You may need to change that as I wrote above

        }).valueChanges
        .subscribe((data: any) => {
          foo();
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of implementing ngOninit with asynchronous data involves handling data that may take

Within the ngOnInit method, I am calling a service method and assigning the return value to a member variable. However, when trying to access this variable later in the ngOnInit again, it seems that due to synchronization issues, the value has not been ass ...

Encountering an error of undefined upon submission of a form while utilizing ng

Sorry if this question has been asked before, but I've searched extensively online and still can't find a solution. I'm new to Angular and TypeScript and I may be overlooking something simple, but I can't get it to work. Any help would ...

Currently, I am working with Angular 11 and encountered some errors while trying to embark on a new project

Command: ng serve Error: Cannot find module '@angular-devkit/build-angular/package.json' View details in "/tmp/ng-lQbnUK/angular-errors.log". These errors occurred when I tried to create the project: Installing packages (npm)... npm WARN depreca ...

Typescript may fall short in ensuring type safety for a basic reducer

I have been working on a simple reducer that uses an object to accumulate values, aiming to maximize TS inference. However, I am facing difficulties in achieving proper type safety with TypeScript. The issue arises when the empty object does not contain an ...

Leveraging services in Angular: accessing directly in view or via component

I am currently working on an application that consists of multiple pages, each with their own components. I have a single config.service.ts file where the debug mode is set as a boolean. Within my views, depending on this setting, I need to show buttons, ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

What is the best way to compare dates for a deadline using Angular and CSS?

Having recently delved into Angular 8, I just picked up on how to convert timestamps to strings using interpolation and .toMillis. However, I am looking to enhance this feature in my project app. I'm currently working on comparing the date saved in m ...

Having trouble executing the typescript build task: Command 'C:Program' is not valid as an internal or external command

I'm currently working on converting typescript code to JavaScript and have been following the steps outlined in the documentation. To automate the compilation of .ts files, I set up a watch task triggered by pressing Ctrl+Shift+B. However, upon runni ...

What is the correct regex expression for validating decimal numbers between 1.0 and 4.5?

I'm having trouble creating an expression to validate numbers between 1.0 to 4.5 accurately. The current expression I'm using is not working as intended: /^[1-4]{0,1}(?:[.]\d{1,2})?$/ The requirement is to only allow values between 1.0 to ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...

Determine an expression based on a string in Typescript

Looking at the code snippet below, everything appears to be in order (view playground): type PathParam<T> = T extends `${string}:${infer U}` ? U : never; type Param = PathParam<"/post/:post_id">; // type Param = "post_id" ...

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Using Angular 2 to assign unique ids to checkbox values

Is there a way to retrieve the value of a checkbox in Angular 2 without needing an additional Boolean variable? I am trying to toggle the enabled/disabled state of an input field based on the selection of a checkbox. While I know this can be accomplished ...

Leverage a custom server (such as NestJS) within NextJS to dynamically render targeted pages

I am experimenting with using NestJS as a custom server for NextJS, following the instructions in this article. Here is a simplified version of the code: @Controller('/') export class ViewController { @Get('*') async static(@Req() r ...

Setting up a ts-node project with ECMAScript modules. Issue: Unrecognized file extension ".ts"

I am currently in the process of setting up a minimalistic repository that incorporates ts-node and ESM for a project. Despite the existence of previous inquiries on this topic, I have encountered numerous outdated responses. Even recent answers appear to ...

I encountered an issue while trying to install the latest version of AngularFire, receiving an error

Recently, I initiated a new Angular Material project and encountered the following errors: moblizeit@Vikrams-MBP scanbuddyadmin % ng add @angular/fire@latest ℹ Using npm as the package manager ⚠ There are unmet peer dependencies within the package. Add ...

Looking for a way to dynamically append a child element within another child

Struggling to include a new child within a specific child in Json myObject:any[] = []; this.myObject = { "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" }, } } addF ...

Why won't T.chain chain properly in Effect-ts?

I have a simple program that I've been working on: import * as T from "@effect-ts/core/Effect"; import { pipe } from "@effect-ts/core/Function"; import { tag } from "@effect-ts/core/Has"; interface ConsoleModule { log: ...

What is the best way to ensure that a class instance only receives the necessary properties?

In my code, I have a function that takes in an object called DataObject and uses certain properties from it to create instances of a class. To determine which data object items should be assigned to which class properties, I use mappings in the form of a ...

The loading time for the Docker index HTML file page is unacceptably slow

Sample Dockerfile: FROM ubuntu:22.04 RUN apt-get update RUN apt-get install -y nginx COPY -r dist/ /var/www/html/ CMD service nginx start && tail -F /var/log/nginx/error.log After that, run the following commands: docker build -t website . docker ...