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.
- Create a local query that will read data only from the cache.
- Create a cache that defines a procedure for the query to read data from local values.
- 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
Post a Comment