3

Apollo Client with GraphQL: Why You Should Try It

 1 year ago
source link: https://keyholesoftware.com/2023/01/16/apollo-client-state-management-for-graphql-made-easy/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Apollo Client with GraphQL

In this post, we will explore Apollo Client integrated with a React application and how it provides an abstraction layer between a JavaScript application and a GraphQL server. The features Apollo Client offers make it a prime choice for devs also using GraphQL.

We’ll begin by discussing what Apollo Client is and how it can be advantageous over other state management libraries. And finally, we will look at some example React queries for retrieving and mutating data.

Let’s get started.

What Is Apollo Client?

Apollo Client is a popular state management library built for JavaScript applications that interact with a GraphQL server. It allows easy solutions for handling GraphQL data including data fetching, caching, real-time subscriptions, and error handling. Additionally, Apollo Client has a large and active community with many resources and support for developers.

Apollo Client can be used in many different JavaScript libraries including Angular, Vue.JS, and React. This allows for easy integration into new and existing projects without having to rewrite code.

Why Use Apollo Client?

When using a GraphQL server, Apollo Client is a great choice for a front-end state management tool. The advantage of Apollo Client over other libraries such as Redux or Recoil is that it provides features specifically designed for GraphQL. Some of these features include:

  • Data Management: Apollo Client provides API for querying and modifying data, allowing for easy state management of an application.
  • Built-In Caching: By caching query results, Apollo Client can reduce the refetching of data that has already been retrieved.
  • Error Handling: Apollo Client has built-in error handling when querying or updating data. This helps simplify both error handling and error display to users.
  • Optimistic UI: Apollo Client will temporarily display the result of a mutation before the server has confirmed the change. Once the operation is complete, it will replace the optimistic data. This can make an application feel more responsive.
  • Developer Tooling: Apollo has a suite of developer tools that can be utilized for debugging and application support.

Set Up

The following command will install the Apollo Client and GraphQL dependencies needed.

npm install @apollo/client graphql

Next, we will define a function to return an Apollo Client with reference to a GraphQL server. This will also set up an in-memory cache.

import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
});

To finish setup, we have to wrap the React app with an ApolloProvider. This will allow any subcomponent access to the GraphQL data.

Wrapping can be done at any level, but I recommend putting it somewhere high in the component tree, above any component that will need to utilize it.

import { ApolloProvider } from '@apollo/client';
<ApolloProvider client={client}>
<App />
</ApolloProvider>

Queries

Now that dependencies have been installed and the application is properly set up, the application is equipped to start querying.

Apollo Client provides several custom React hooks for querying GraphQL data. For the sake of brevity in this post, we will only cover useQuery (used for retrieving data) and useMutation (used for modifying data).

useQuery

The useQuery hook allows a GraphQL query to be executed inside a functional component. When using the hook, it will provide an object containing the dataset returned from the query, as well as some other metadata such as any loading and error states.

On component render, the hook will execute the given query. It will return the results in the data property, the current loading state in the loading property, and any errors in error.

import { useQuery, gql } from '@apollo/client';
const { loading, error, data } = useQuery(gql`
query {
user {
name
email
}
}
`);

useMutation

The useMutation hook is used for executing a GraphQL mutation in a functional component. The response is made of two parts.

The first is the mutation function that executes the mutation against the given GraphQL server. The second part is the object containing the results of the mutation, as well as the loading and error states.

The mutation function can be called with variables and options, and it returns a Promise that will resolve the mutation result.

import { useMutation, gql } from '@apollo/client';
const [createUser, { data, loading, error }] = useMutation(gql`
mutation createUser($name: String!) {
createUser(name: $name) {
id
name
completed
}
}
`);

Conclusion

With Apollo Client, it is easy to create a JavaScript application with reliable state management.

The features provided make it a preferable solution over other libraries specifically when partnered with a GraphQL server. The built-in hooks are simple and easy to use and give a sense of familiarity when compared to React hooks like useState.

I hope this post has served to convince you to give Apollo Client a try, especially if you’re also using GraphQL. Let me know what you think in the comments below, and be sure to subscribe to the Keyhole Dev Blog for more great content.

Continued Reading

For continued reading on Apollo Client or more example code, here are some resources I found helpful.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK