How to setup React + Graphql (query + subscriptions)

Krina Wibisana
bhinneka-tech
Published in
2 min readJan 2, 2023
https://www.apollographql.com/blog/community/seamless-integration-for-graphql-and-react-6ffc0ad3fead/

What is Graphql?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
https://graphql.org/

What is Queries?
As the name suggests, Query, GraphQL can query what fields we will use, without having to accept all fields, and with queries, it makes it easier for us as the frontend to handle responses from the backend.

What is Subscriptions?
Subscriptions, in my opinion, a very good tool for dealing with data that requires dynamic changes, because here we will use WebSockets to do subscriptions. Subscriptions are especially good for real-time applications, such as chat applications.

Pssst, I will not explain how to set up React + GraphQL…. Only setup for GraphQL utils to handle Query + Subscriptions.

First of all, install the dependencies below

yarn add @apollo/client graphql

Then set up utils for GraphQL Query + Subscriptions.

import { ApolloClient, InMemoryCache, split, HttpLink, from } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { onError } from '@apollo/client/link/error';
import { getMainDefinition } from '@apollo/client/utilities';

// use import.meta.env instead process.env if you started your project using Vite
export const urlGraphql = `${import.meta.env.VITE_HOST_API}/graphql`;
export const wsGraphql = `${import.meta.env.VITE_HOST_WS_API}/graphql`;

// create your error handler
const handleError = onError(({ graphQLErrors }) => {
if (graphQLErrors?.[0]?.extensions?.code === 401) {
setTimeout(() => {
window.location.href = '/login';
});
}
});

const httpLink = new HttpLink({
uri: urlGraphql,
headers: {
// your headers
}
});

const wsLink = new WebSocketLink({
uri: wsGraphql,
options: {
reconnect: true
}
});

// Query + Subscriptions handler
const handleValidateLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
},
wsLink,
httpLink
);

// create client variable and pass this variable to <ApolloProvider client={client} />
export const client = new ApolloClient({
link: from([handleError, handleValidateLink]),
cache: new InMemoryCache()
});

Voila, now you can use Query and Subscription for your React project, use useQuery and useSubscription to handle GraphQL query and subscriptions.

Thank you!

--

--