How to Build a Realtime Chat App with React and GraphQL

GraphQL and React are a match made in heaven. Their ecosystem provides a lot of tools to simplify common web programming tasks including realtime integrations. In this article, you're going to learn how to use only React and GraphQL to make a realtime apps (precisely a chat app).

I'm assuming you know the basic concepts of GraphQL and React. Therefore, this article will focus on showing you how to build a realtime app with both tools while skipping explanations for basic concepts.

Yes I understand these terms can be daunting. They were not so easy for me to get along with as well but with practice and knowing the fundamental knowledge, you will start getting a hang of it.

GraphQL

Basically, GraphQL is a query spec that is built around the Graph algorithm. It's developed by Facebook and it's so powerful that it seems to be replacing the REST we love. Rather than just sending JSON payloads through REST to a server, then the server in-turn queries a database, GraphQL gives you the power to serve these queries right from the client. This way you end up with just what the client needs and not what the REST endpoint exposed.

Apollo

GraphQL is just a spec that you can follow to build your own implementation. But that's a hard journey. This is why tools like Apollo were built to serve as GraphQL clients. From a beginner perspective, you can see it as an SDK for interacting with a GraphQL server that follows a GraphQL spec.

Graphcool

Speaking of servers, the process of setting up one and the tooling involved can also get overwhelming. Sometimes you might even get it wrong, hence exposing your products to security vulnerabilities. Graphcool is a highly extensive hosted GraphQL server that you can work with. You can manipulate anything on the server using its serverless functions. The service has a free tier that is generous enough to get you into business without paying a dime.

create-react-app has been developers favorite tool for scaffolding React apps. We're just going to stick to it because there is a high chance you know how it works and probably used it before. Scaffold a new project in React by running the following command:

create-react-app graphql-chat

This would create a new folder named graphql-chat and download all the necessary React files you need to work with.

Rather than have a local server running, we can use an existing free hosted service to setup a GraphQL instance. This is not only free but less tasking and easier to get started with. Graphcool is fantastic for small projects and also amazing for larger projects when your app grows.

To setup an instance, you need to first install the Graphcool CLI tool. This tool exposes commands for creating new GraphQL servers, updating them, as well as deploying them. It can also be used to manage the Graphcool cloud functions. Run the following command to install:

npminstall -g graphcool-framework

Navigate to the React app we just setup through the terminal and start a new Graphool server:

For our chat app, we just need to focus on the types.graphql file generated in the server folder. This is where you tell GraphQl what the structure of your data looks like. It's known as a type definition. Replace it's content with the following:

The constructor function takes an object with config options. The uri is required and should be the same as the Subscriptions API URI you received after deploying. The options are optional, but we are using the reconnect option to ask WebSocket to try reconnecting after a failed attempt.

We are not just making a WebSocket connection. We also need to setup an HTTP connection for request-response operations. Add this right below the WebSocket link setup:

const httpLink =newHttpLink({ uri:'[SIMPLE API URI]'})

The same as the WebSocketLink constructor but uses the Simple API URI. We don't need to pass in any configuration option.

At this point, we have two links. How do we tell the server when to use which. This is achievable using the split method we imported above:

The split method takes three arguments. The first is a test that returns a boolean. If the boolean value is true, the request is forwarded to the second (wsLink) argument. If false, it's forwarded to the third (httpLink) argument.

Now we can create an Apollo client with the returned link:

const client =newApolloClient({
link,
cache:newInMemoryCache()})

You can make requests directly to your server using the URLs provided. This is a bit messier than using a wrapper library that provides functionalities to simplify server interaction. Apollo is one of such libraries.

Mutations in GraphQL are used to create, edit, and delete values from your database. Where a query is the R (Read) in CRUD, a mutation can be the CUD (Create, Update, Delete). We are already able to read existing messages in our chat app. Next thing we should worry about is creating those messages from our React app.

The mutation is a lot like a query but receives parameters -- content and from. We need to wrap the App component with both this mutation and our existing query. For this reason, we also import the compose method and use this method to wrap both HOCs.

In the render method, we can have an input element that collects these message contents:

Subscriptions in GraphQL are used to listen for changes by connected clients. These clients can act on these changes accordingly. Probably by updating the user interface with the changed data or even sending push notifications. The underlying technology that powers subscriptions is the well known WebSockets.

The allChatsQuery exposes a subscribeToMore method. Once this method is called, it opens up a channel for realtime communication. The method takes an object which we can define the query document and an updateQuery method.

The document defines a subscription and listens for when a mutation occurs on the Chat entity before triggering an event. The update method receives the old and new value, and we are using these new value to update the old value.

You can kick off this subscription in the componentDidMount lifecycle method:

You already learned a lot, but there is more to GraphQL. You can dig our Scotch articles on GraphQL to discover more. The How to GraphQL tutorials are also excellent and walks you through steps on learning about the GraphQL fundamentals. Feel free to hit the comments section if you run into issues or find a bug.

Jobs!

If you’re familiar with popular JavaScript frontend frameworks like React, Angular, etc, then the concept of ECMAScript won’t be entirely new to you. ES Modules have the import and export syntax we see often in frontend frameworks. Node uses CommonJS which re...