Full-stack GraphQL App with React and Apollo - #15

Опубликовано: 08 Июнь 2024
на канале: Everyday Be Coding
111
0

#GraphQL #ApolloServer #ReactJS #FullStackDevelopment #WebDevelopment #JavaScript #APIs #FrontEndDevelopment #BackEndDevelopment #WebApps #RealTimeData #Coding #Programming #SoftwareEngineering #JavaScriptFrameworks #GraphQLAPI #ReactDevelopers #CodeWithReact #WebDevCommunity #techtutorials

Building a full-stack GraphQL app with React and Apollo involves several steps. Here's a concise guide to get you started:

Backend Setup with Apollo Server
Install Dependencies:
npm install apollo-server graphql

Create Apollo Server:
JavaScript code
const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
type Query {
hello: String
}`;

const resolvers = {
Query: {
hello: () = 'Hello world!',
},
};

const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) = {
console.log(`🚀 Server ready at ${url}`);
});
Frontend Setup with React and Apollo Client
Install Dependencies:
npx create-react-app my-app
cd my-app
npm install @apollo/client graphql
Configure Apollo Client:

JavaScript code
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import App from './App';

const client = new ApolloClient({
uri: 'http://localhost:4000',
cache: new InMemoryCache(),
});

ReactDOM.render(
ApolloProvider client={client}
App /
/ApolloProvider,
document.getElementById('root')
);
Create a React Component to Fetch Data:

JavaScript code
// src/App.js
import React from 'react';
import { useQuery, gql } from '@apollo/client';

const HELLO_QUERY = gql`
query GetHello {
hello
};

function App() {
const { loading, error, data } = useQuery(HELLO_QUERY);

if (loading) return p Loading.../p;
if (error) return pError :(/p;
return h1{data.hello}/h1;
}

export default App;
Adding Subscriptions for Real-Time Updates
Set Up WebSocket Link:

npm install @apollo/client subscriptions-transport-ws
Configure WebSocket Link in Apollo Client:

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

const httpLink = new HttpLink({
uri: 'http://localhost:4000',
});

const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/graphql`,
options: {
reconnect: true,
},
});

const splitLink = split(
({ query }) = {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);

const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
Implement Subscription in Backend:

JavaScript code:
const { ApolloServer, gql, PubSub } = require('apollo-server');

const pubsub = new PubSub();
const MESSAGE_ADDED = 'MESSAGE_ADDED';

const typeDefs = gql`
type Message {
id: ID!
content: String!
}
type Query {
messages: [Message!]
}
type Mutation {
addMessage(content: String!): Message!
}
type Subscription {
messageAdded: Message!
}`;

const resolvers = {
Query: {
messages: () = messages,
},
Mutation: {
addMessage: (parent, { content }) = {
const message = { id: messages.length + 1, content };
messages.push(message);
pubsub.publish(MESSAGE_ADDED, { messageAdded: message });
return message;
},
},
Subscription: {
messageAdded: {
subscribe: () = pubsub.asyncIterator([MESSAGE_ADDED]),
},
},
};

const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, res }) = ({ req, res, pubsub }),
});

server.listen().then(({ url }) = {
console.log(`🚀 Server ready at ${url}`);
});

Use Subscription in React Component:
JavaScript code
import { useSubscription, gql } from '@apollo/client';

const MESSAGE_ADDED = gql`
subscription OnMessageAdded {
messageAdded {
id
content
}
}`;

function Messages() {
const { data, loading } = useSubscription(MESSAGE_ADDED);
if (loading) return pLoading.../p;
return pNew message: {data.messageAdded.content}/p;
}

export default Messages;
This setup provides a complete flow for building a full-stack GraphQL application with real-time capabilities using React and Apollo. For more detailed guides and advanced features, refer to the official Apollo documentation.


Смотрите видео Full-stack GraphQL App with React and Apollo - #15 онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Everyday Be Coding 08 Июнь 2024, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 11 раз и оно понравилось людям.