Show List
Interview Questions A
GraphQL's flexibility and ability to request precisely the data you need make it a great fit for frontend development. You can integrate GraphQL with popular frontend frameworks like React, Angular, and Vue.js etc.
Here is an example of integrating GraphQL with React. There are various clients available for the integration. We will be using Apollo Client.
1) Create the React application
npx create-react-app graphql-react-app
2) Install Dependency - Apollo client
npm install @apollo/client graphql
Application:
index.js
import { React } from "react";import * as ReactDOM from "react-dom/client";import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";import App from "./App";const client = new ApolloClient({uri: "http://localhost:8080/graphql",cache: new InMemoryCache(),});const root = ReactDOM.createRoot(document.getElementById("root"));root.render(<ApolloProvider client={client}><App /></ApolloProvider>);
App.js
import { useQuery, gql } from "@apollo/client";const GET_BOOK_BY_ID = gql`query GetBookById($id: ID) {bookById(id: $id) {idnameauthor {idfirstNamelastName}}}`;function DisplayBook() {const { loading, error, data } = useQuery(GET_BOOK_BY_ID, {variables: { id: "1" },});if (loading) return <p>Loading...</p>;if (error) return <p>Error :(</p>;const book = data.bookById;return (<div><h2>Book Details</h2><p>Title: {book.name}</p><p>Author: {book.author.firstName} {book.author.lastName}</p></div>);}export default function App() {return (<div><br /><DisplayBook /></div>);}
When the React application is run, the data coming from GraphQL can be viewed on the UI:
Source code:
https://github.com/it-code-lab/graphql-react-app
Leave a Comment