#GraphQL #ApolloServer #ReactJS #WebDevelopment #RealTimeData #JavaScript #FullStackDevelopment #APIs #WebSockets #GraphQLSubscriptions #FrontEndDevelopment #BackEndDevelopment #JavaScriptFrameworks #ProgrammingTutorials #CodeWithReact #GraphQLAPI #SoftwareEngineering #TechTutorials #DevCommunity #codingtips
Implementing GraphQL subscriptions with Apollo Server and React allows real-time data updates in your application. Here's a step-by-step guide on how to do it:
Setting up Apollo Server:
Install required packages:
Code
npm install apollo-server graphql
Create your Apollo Server:
JavaScript code
const { ApolloServer, PubSub } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const pubsub = new PubSub();
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) = ({ req, res, pubsub }),
});
server.listen().then(({ url }) = {
console.log(`🚀 Server ready at ${url}`);
});
Define your GraphQL schema (schema.js):
Code:
type Post {
id: ID!
content: String!
}
type Query {
posts: [Post!]!
}
type Mutation {
createPost(content: String!): Post!
}
type Subscription {
postCreated: Post!
}
Implement your resolvers (resolvers.js):
JavaScript code:
let posts = [];
const resolvers = {
Query: {
posts: () = posts,
},
Mutation: {
createPost: (parent, { content }, { pubsub }) = {
const post = { id: String(posts.length + 1), content };
posts.push(post);
pubsub.publish('POST_CREATED', { postCreated: post });
return post;
},
},
Subscription: {
postCreated: {
subscribe: (parent, args, { pubsub }) = {
return pubsub.asyncIterator('POST_CREATED');
},
},
},
};
module.exports = resolvers;
Setting up Apollo Client with React:
Install required packages:
npm install @apollo/client graphql
Create your Apollo Client:
JavaScript code
import { ApolloClient, InMemoryCache, ApolloProvider, gql } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
const link = new WebSocketLink({
uri: 'ws://localhost:4000/graphql',
options: {
reconnect: true,
},
});
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
export default client;
Use ApolloProvider to wrap your React app:
Code :
import React from 'react';
import { ApolloProvider } from '@apollo/client';
import client from './client';
import PostList from './PostList';
function App() {
return (
ApolloProvider client={client}
div
h2 Posts /h2
PostList /
/div
/ApolloProvider
);
}
export default App;
Implement your React component (PostList.js):
JavaScript code
import React from 'react';
import { useQuery, useSubscription } from '@apollo/client';
import { gql } from 'graphql-tag';
const POSTS_QUERY = gql`
query {
posts {
id
content
}
}
`;
const POST_CREATED_SUBSCRIPTION = gql`
subscription {
postCreated {
id
content
}
}
`;
function PostList() {
const { loading, error, data } = useQuery(POSTS_QUERY);
const { data: subscriptionData } = useSubscription(POST_CREATED_SUBSCRIPTION);
if (loading) return p Loading.../p;
if (error) return pError :(/p;
const posts = subscriptionData ? [...data.posts, subscriptionData.postCreated] : data.posts;
return (
ul
{posts.map((post) = (
li key={post.id} {post.content}/li
))}
/ul
);
}
export default PostList;
Now, your React application should be able to subscribe to new posts in real-time using GraphQL subscriptions with Apollo Server and React. Make sure your Apollo Server is running alongside your React application for this setup to work.