English 中文(简体)
GraphQL - React Integration
  • 时间:2024-09-17

GraphQL - React Integration


Previous Page Next Page  

React is a Javascript pbrary for building user interfaces. This chapter explains how one can integrate GraphQL with a React apppcation.

Illustration

The quickest way to set up a react project is by using the Create React App tool. In the subsequent sections, we will learn how to set up both the Server and the Cpent.

Setting up the Server

For setting up the Server, follow the below steps −

Step 1 − Download and Install Required Dependencies for the Project

Create a folder react-server-app. Change your directory to react-server-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter.

Step 2 − Create a Schema

Add schema.graphql file in the project folder react-server-app and add the following code −

type Query
{
   greeting: String
   sayHello(name:String!):String
}

The file has defined two queries – greeting and sayHello. The sayHello query accepts a string parameter and returns another string. The parameter to the sayHello() function is not null.

Step 3 − Create Resolvers

Create a file resolvers.js in the project folder and add the following code −

const Query =
{
   greeting: () =>  Hello GraphQL  From TutorialsPoint !!  ,
   sayHello:(root,args,context,info) =>  `Hi ${args.name} GraphQL server says Hello to you!!`
}
module.exports = {Query}

Here greeting and sayHello are two resolvers. In the sayHello resolver, the value passed to the name parameter can be accessed through args. To access resolver functions outside the module, Query object has to be exported using module.exports.

Step 4 − Run the Apppcation

Create a server.js file. Refer step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a cpent to test the apppcation.

Open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor −

{
   greeting,
   sayHello(name:"Mohtashim")
}

The response from the server is given below −

{
   "data": {
      "greeting": "Hello GraphQL  From TutorialsPoint !!",
      "sayHello": "Hi Mohtashim GraphQL server says Hello to you!!"
   }
}

Setting up the Cpent

Open a new terminal for cpent. The server terminal should be kept running before executing the cpent apppcation. React apppcation will be running on port number 3000 and server apppcation on port number 9000.

Step 1 − Create a React Project hello-world-cpent

In the cpent terminal, type the following command −

npx create-react-app hello-world-cpent

This will install everything needed for a typical react apppcation. The npx utipty and create-react-app tool create a project with name hello-world-cpent. Once the installation is completed, open the project in VSCode.

Step 2 − Start hello-world-cpent

Change the current folder path in the terminal to hello-world-cpent. Type npm start to launch the project. This will run a development server at port 3000 and will automatically open the browser and load the index page.

This is shown in the screenshot given below −

Creating React Project

Step 3 − Modify the App Component

In the App.js inside src folder, add two functions, one to load greeting and another to load sayHello messages.

Following is the loadGreeting function which sends GraphQL query for greeting.

async function loadGreeting() {
   const response = await fetch( http://localhost:9000/graphql , {
      method: POST ,

      headers:{ content-type : apppcation/json },
      body:JSON.stringify({query: {greeting} })
   })

   const rsponseBody = await response.json();
   return rsponseBody.data.greeting;

   console.log("end of function")
}

Following is the loadSayhello function which sends GraphQL query for sayHello −

async function  loadSayhello(name) {
   const response = await fetch( http://localhost:9000/graphql , {
      method: POST ,
      headers:{ content-type : apppcation/json },
      body:JSON.stringify({query:`{sayHello(name:"${name}")}`})
   })
}

The complete App.js file is shown below −

import React, { Component } from  react ;
import logo from  ./logo.svg ;
import  ./App.css ;

async function loadGreeting() {
   const response =  await fetch( http://localhost:9000/graphql , {
      method: POST ,
      headers:{ content-type : apppcation/json },
      body:JSON.stringify({query: {greeting} })
   })
   const rsponseBody =  await response.json();
   return rsponseBody.data.greeting;
   console.log("end of function")
}

async function  loadSayhello(name) {
   const response =  await fetch( http://localhost:9000/graphql , {
      method: POST ,
      headers:{ content-type : apppcation/json },
      body:JSON.stringify({query:`{sayHello(name:"${name}")}`})
   })
   const rsponseBody =  await response.json();
   return rsponseBody.data.sayHello;
}

class App extends Component {
   constructor(props) {
      super(props);
      this.state =  {greetingMessage:  ,sayHelloMessage:  ,userName:  }
      this.updateName =  this.updateName.bind(this);
      this.showSayHelloMessage =  this.showSayHelloMessage.bind(this);
      this.showGreeting =  this.showGreeting.bind(this);
   }
   
   showGreeting() {
      loadGreeting().then(g => this.setState({greetingMessage:g+" :-)"}))
   }
   
   showSayHelloMessage() {
      const name = this.state.userName;
      console.log(name)
      loadSayhello(name).then(m => this.setState({sayHelloMessage:m}))
   }
   
   updateName(event) {
      this.setState({userName:event.target.value})
   }
   render() {
      return (
         <span className = "App">
            <header className = "App-header">
               <img src = {logo} className = "App-logo" alt = "logo" />
               <h1 className = "App-title">Welcome to React</h1>
            </header>
            <br/><br/>
            <section>
               <button id = "btnGreet" onCpck = {this.showGreeting}>Greet</button>
               <br/> <br/>
               <span id = "greetingDiv">
                  <h1>{this.state.greetingMessage}</h1>
               </span>
            </section>
            
            <hr/>
            
            <section>
               Enter a name:<input id = "txtName" type = "text" onChange = {this.updateName}
               value = {this.state.userName}/>
               <button id = "btnSayhello" onCpck = {this.showSayHelloMessage}>SayHello</button>
               <br/>
               user name is:{this.state.userName}    <br/>
               <span id = "SayhelloDiv">
                  <h1>{this.state.sayHelloMessage}</h1>
               </span>
            </section>
         </span>
      );
   }
}

export default App;

Once both the apppcations are running, cpck on the greet button. Next, enter a name in the textbox and cpck on sayHello button. The output will be as given below −

React Output Hello GraphQL Advertisements