Skip to main content

Utilise GraphQL and Apollo Client for Maintaining React State

One library that is quite popular to allow our application to interact with the GraphQL server is Apollo Client (@apollo/client). It has support for several popular client libraries including React. It also provides cache management functionality to improve the performance of the application when interacting with GraphQL. Rather than integrating another library to manage our application state, we can leverage what Apollo Client already has to maintain the state.

The solution is achieved by creating a customised query to load the result from a local variable or storage. Then, the query is executed like other queries using useQuery().

The steps are as follows.

  1. Create a local query that will read data only from the cache.
  2. Create a cache that defines a procedure for the query to read data from local values.
  3. Call the query anytime we want to read the state value.

For instance, we want to read the information of the current user that has successfully logged in to our application. The information has been stored in the local storage. Firstly, we create the definition of the GraphQL query that will only read data from the cache using @client syntax.

const GET_USER_INFO = gql`
  query GetUserInfo {
    userInfo @client
  }
`;

Before we create the cache, we need to create a reactive variable that can be used globally in the application to both store and read any value using the makeVar function. Then, we can create a cache with a query configuration to read a value from the reactive variable. In this example, the value stored is only about the logged-in status of the user.

import { makeVar, InMemoryCache } from '@apollo/client';

export const userInfoVar = makeVar({
  isLoggedIn: !!localStorage.getItem('token'),
});

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        userInfo: {
          read() {
            return userInfoVar();
          },
        },
      },
    },
  },
});

Then, we should include the cache definition in the Apollo client instance.

const client = new ApolloClient({
  link,
  cache,
  resolvers,
});

We can test calling the query on a page just like other GraphQL queries.

const { data, loading, error } = useQuery(GET_USER_INFO);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error! Note not found</p>;
return !data.userInfo.isLoggedIn ? null : children;

We can call the reactive variable with the updated value as the argument for updating the value.

//...
userInfoVar({ ...userInfoVar(), isLoggedIn: true });
//...

Comments

  1. Thanks for creating such an outstanding, dayzsalauncher.org experience filled with valuable content and intuitive navigation. The website provides practical knowledge while making every visit informative, comfortable, and enjoyable.

    ReplyDelete
  2. My appreciation goes to everyone behind windterm.io for creating such an informative and reliable platform. The website provides valuable knowledge, simple navigation, and excellent usability that benefits visitors from around the world.

    ReplyDelete

Post a Comment

Popular posts from this blog

Deploying a Web Server on UpCloud using Terraform Modules

In my earlier post , I shared an example of deploying UpCloud infrastructure using Terraform from scratch. In this post, I want to share how to deploy the infrastructure using available Terraform modules to speed up the set-up process, especially for common use cases like preparing a web server. For instance, our need is to deploy a website with some conditions as follows. The website can be accessed through HTTPS. If the request is HTTP, it will be redirected to HTTPS. There are 2 domains, web1.yourdomain.com and web2.yourdomain.com . But, users should be redirected to "web2" if they are visiting "web1". There are 4 main modules that we need to set up the environment. Private network. It allows the load balancer to connect with the server and pass the traffic. Server. It is used to host the website. Load balancer. It includes backend and frontend configuration. Dynamic certificate. It is requ...

Rangkaian Sensor Infrared dengan Photo Dioda

Keunggulan photodioda dibandingkan LDR adalah photodioda lebih tidak rentan terhadap noise karena hanya menerima sinar infrared, sedangkan LDR menerima seluruh cahaya yang ada termasuk infrared. Rangkaian yang akan kita gunakan adalah seperti gambar di bawah ini. Pada saat intensitas Infrared yang diterima Photodiode besar maka tahanan Photodiode menjadi kecil, sedangkan jika intensitas Infrared yang diterima Photodiode kecil maka tahanan yang dimiliki photodiode besar. Jika  tahanan photodiode kecil  maka tegangan  V- akan kecil . Misal tahanan photodiode mengecil menjadi 10kOhm. Maka dengan teorema pembagi tegangan: V- = Rrx/(Rrx + R2) x Vcc V- = 10 / (10+10) x Vcc V- = (1/2) x 5 Volt V- = 2.5 Volt Sedangkan jika  tahanan photodiode besar  maka tegangan  V- akan besar  (mendekati nilai Vcc). Misal tahanan photodiode menjadi 150kOhm. Maka dengan teorema pembagi tegangan: V- = Rrx/(Rrx + R2) x Vcc V- = 150 / (1...

Armin or Commander Erwin

In the moment of conflict in the scout team, who will be revived?

What's Good About Strapi, a Headless CMS

Recently, I've been revisiting Strapi as a solution for building backend systems. I still think this headless CMS can be quite useful in certain cases, especially for faster prototyping or creating common websites like company profiles or e-commerce platforms . It might even have the potential to handle more complex systems. With the release of version 5, I'm curious to know what updates it brings. Strapi has launched a new documentation page, and it already feels like an improvement in navigation and content structure compared to the previous version. That said, there's still room for improvement, particularly when it comes to use cases and best practices for working with Strapi. In my opinion, Strapi stands out with some compelling features that could catch developers' attention. I believe three key aspects of Strapi offer notable advantages. First, the content-type builder feature lets us design the data structure of an entity or database model , including ...

Armin and Eren VS Colossal Titan

The trick was unexpected and caught Bertolt off guard.

Kenshin VS The Assassin

It is an assassin versus assassin.