Modern applications are getting more real-time. Notification updates, chat messaging applications, and financial market updates are all examples of real-time updates in online apps. With a feature called subscriptions, GraphQL makes it simple to create apps with low latency, and real-time updates.
In this blog, we will discuss:
- Polling
- WebSockets
- GraphQL Subscriptions
- Apollo Client
- Features
- Community Integrations
- Why Apollo Client?
- Case Studies
- Hands-on
- Conclusion
There are several ways in which we can architect real-time applications. The three most common ways are:
Polling
Polling in simple terms is making HTTP calls to a web server at given intervals, let us say 1 second, two seconds, and so on. This architecture is expensive because it will increase the load on the server due to the many requests being made per second. The way HTTP works is that the connection is closed each time the request is finished and another connection is opened when the response is sent from the server to the client.
WebSockets
WebSocket is a computer communication protocol that allows the server and web client to communicate over an open connection. Websockets are full-duplex or bi-directional meaning that information/data flow is from server to client and vice-versa as soon as the data is received or an event is triggered.
GraphQL Subscriptions
GraphQL Subscriptions are the web socket implementation of GraphQL. It is much simplified for you to allow you to focus on the end goal which is receiving real-time data and triggering the subsequent events instead of configuring web socket events from scratch.
Apollo Client
Apollo Client is a comprehensive JavaScript framework for managing state, enabling you to handle both local and remote data using GraphQL. With Apollo Client, you can easily manage the state of your application and simplify data fetching, all while leveraging the power and flexibility of GraphQL.
Apollo Client assists you in structuring code in a cost-effective, predictable, and declarative manner that is consistent with modern development practices. The core @apollo/client library includes React integration, while the Apollo community as a whole maintains integrations for additional popular view layers.
Features of Apollo Client
- Declarative Data Fetching: Allows you to write a query and retrieve data without having to manually track loading states.
- Outstanding Developer Experience: Take advantage of useful TypeScript, Chrome / Firefox devtools, and VS Code tooling.
- Designed for Modern React: Use the most recent React features, such as hooks.
- Adopt Apollo in Stages: Drop Apollo into any JavaScript app and integrate it feature by feature.
- Universal Compatibility: Use any build configuration and any GraphQL API.
- Community-driven: Share your knowledge with thousands of GraphQL developers.
Community Integrations
Apart from React, many other libraries and languages are supported by Apollo Client:
- JavaScript
- Angular
- Vue
- Svelte
- Solid.js
- Ember
- Meteor (thanks to DDP-Apollo)
- Web Components
- Apollo Elements
- Native Mobile
- Native iOS with Swift
- Native Android with Java and Kotlin
Why Choose Apollo Client?
- Obtaining declarative data
- Bringing together local and remote data
- Caching with no configuration
- A robust environment
Apollo Client Case Studies
Apollo Client has become a trusted choice for a wide range of companies, from large enterprises to startups, as they seek to power their most critical web and native applications. Many organizations have experienced the benefits of transitioning to GraphQL and Apollo, such as simplified workflows for their engineers and improved products for their customers.
- The New York Times: Discover how The New York Times transitioned from Relay to Apollo and added features such as SSR and persistent queries in their app.
- Express: Apollo’s simple pagination assisted the Express eCommerce team in improving important product pages.
- Major League Soccer: By switching from Redux to Apollo for state management, MLS was able to remove almost all of its Redux code.
- Expo: By using Apollo to develop their React Native app, the Expo engineers were able to focus on refining their product rather than writing data-fetching algorithms.
- KLM: Discover how the KLM team used GraphQL and Apollo to scale their Angular app.
Hands-on
In this blog, we are going to create a real-time application that enables all users with access to the application to receive real-time updates when a new user registers into the system. The backend for this is already tackled in a separate blog.
The code used in this blog is found at https://github.com/workfall/workfall-react-graphql
Folder Structure
Installations
First of all, create a new React application using the command:
npx create-react-app <project_name> --template typescript
Next, we install the Apollo client using the command:
yarn add @apollo/client graphql, yarn add subscriptions-transport-ws
And finally,
yarn add formik yup @types/yup.
Code
index.tsx(1):
In this file, we shall do all the necessary configurations required by the Apollo GraphQL client.
We begin by declaring links to the two transport layers which are HTTP and WebSockets. We shall then wrap the root component with the Apollo provider.
index.tsx(2):
App.tsx:
In this file, we shall declare routing for the application, the index route will be the list of users displayed in a table. We shall have another route to navigate to the New User Registration form.
ListUsers.tsx(1):
In this file, we shall write all the logic pertaining to the fetching of the data. We shall start by declaring our GraphQL operations.
In this case, we have a query operation to fetch all the available users and then we have a subscription operation to listen to any new users that will be registered into the system.
ListUsers.tsx(2):
The Apollo client provides us with several hooks to simplify working with GraphQL operations. In the file below, we are utilizing the useQuery and useSubscription hooks.
The useQuery hook will perform a query operation and then you can destructure data, error, and loading from the hook execution results.
In this example, we have used empty curly braces to scope the variables from the useSubscription hook to avoid running into issues with shadow variables.
Table.tsx(1):
In this file, we shall write a reusable and generic table component. The table will receive data passed to it in terms of rows and columns and render it in the UI.
Table.tsx(2):
Table.module.css:
CreateUserForm.tsx(1):
In this file, we shall write a form component to enable us to send user registration information to our GraphQL server.
For form validation, we shall use Yup in conjunction with Formik.
To send a create user request to the server, we perform a mutation operation coupled with the required payload.
CreateUserForm.tsx(2):
CreateUserForm.module.css(1):
CreateUserForm.module.css(2):
We shall test this application on a split screen to see how the data is updated in real-time.
Last, once the client will register a user and you will notice that the new user is automatically added to the existing list.
Conclusion
In this blog, we demonstrated how we can create a real-time application using React and GraphQL subscriptions and the GraphQL Apollo client. In addition to this, we also learned how to perform other GraphQL operations such as queries and mutations on the React client.
Last but not least, we saw how we can configure the Apollo client with React by providing the link chain in terms of the HTTP link and Websocket link.
GraphQL subscriptions are a good choice for using Websockets without dealing with the pain of creating your own WebSocket transport layer. We will come up with more such use cases in our upcoming blogs.
Meanwhile…
If you are a React & GraphQL Lover and want to explore more about the above topics, here are a few of our blogs for your reference:
- Building Real-Time Apps with NestJS and GraphQL Subscriptions
- How to Manage State in a React Application Using Redux?
- How to Build a Hybrid App using React Native?
Stay tuned to get all the updates about our upcoming blogs on the cloud and the latest technologies.
Keep Exploring -> Keep Learning -> Keep Mastering
At Workfall, we strive to provide the best tech and pay opportunities to kickass coders around the world. If you’re looking to work with global clients, build cutting-edge products, and make big bucks doing so, give it a shot at workfall.com/partner today!