GraphQL - React Integration

React è una libreria Javascript per la creazione di interfacce utente. Questo capitolo spiega come integrare GraphQL con un'applicazione React.

Illustrazione

Il modo più rapido per impostare un progetto React è utilizzare lo   strumento Crea app React . Nelle sezioni successive impareremo come configurare sia il Server che il Client.

Configurazione del server

Per configurare il server, seguire i passaggi seguenti:

Passaggio 1: scaricare e installare le dipendenze richieste per il progetto

Crea una cartella react-server-app. Cambia la tua directory in react-server-app dal terminale. Seguire i passaggi da 3 a 5 spiegati nel capitolo Configurazione dell'ambiente.

Passaggio 2: creare uno schema

Inserisci schema.graphql file nella cartella del progetto react-server-app e aggiungi il seguente codice -

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

Il file ha definito due query: greeting e sayHello. La query sayHello accetta un parametro stringa e restituisce un'altra stringa. Il parametro della funzione sayHello () non è nullo.

Passaggio 3: creazione di resolver

Crea un file resolvers.js nella cartella del progetto e aggiungi il seguente codice -

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

Qui saluto e SayHello sono due risolutori. Nel risolutore sayHello, è possibile accedere al valore passato al parametro name tramite args. Per accedere alle funzioni del resolver al di fuori del modulo, l'oggetto Query deve essere esportato utilizzando module.exports.

Passaggio 4: eseguire l'applicazione

Crea un file server.js. Fare riferimento al passaggio 8 nel capitolo Configurazione dell'ambiente. Esegui il comando npm start nel terminale. Il server sarà attivo e funzionante sulla porta 9000. Qui, usiamo GraphiQL come client per testare l'applicazione.

Apri il browser e digita l'URL http://localhost:9000/graphiql. Digita la seguente query nell'editor:

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

Di seguito viene fornita la risposta dal server:

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

Configurazione del client

Apri un nuovo terminale per il cliente. Il terminale del server deve essere mantenuto in esecuzione prima di eseguire l'applicazione client. L'applicazione React verrà eseguita sulla porta numero 3000 e l'applicazione server sulla porta numero 9000.

Passaggio 1: crea un hello-world-client del progetto React

Nel terminale del client, digita il seguente comando:

npx create-react-app hello-world-client

Questo installerà tutto il necessario per una tipica applicazione React. Ilnpx utilità e create-react-appstrumento crea un progetto con il nome hello-world-client. Una volta completata l'installazione, apri il progetto in VSCode.

Passaggio 2: avvia hello-world-client

Cambia il percorso della cartella corrente nel terminale in hello-world-client. Digita npm start per avviare il progetto. Questo eseguirà un server di sviluppo sulla porta 3000 e aprirà automaticamente il browser e caricherà la pagina dell'indice.

Questo è mostrato nella schermata riportata di seguito:

Passaggio 3: modificare il componente dell'app

Nell'App.js all'interno della cartella src, aggiungi due funzioni, una per caricare i messaggi di saluto e un'altra per caricare i messaggi sayHello.

Di seguito è riportata la funzione loadGreeting che invia una query GraphQL per il saluto.

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

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

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

   console.log("end of function")
}

Di seguito è riportato il file loadSayhello funzione che invia query GraphQL per sayHello -

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

Il completo App.js il file è mostrato di seguito -

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':'application/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':'application/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 (
         <div 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" onClick = {this.showGreeting}>Greet</button>
               <br/> <br/>
               <div id = "greetingDiv">
                  <h1>{this.state.greetingMessage}</h1>
               </div>
            </section>
            
            <hr/>
            
            <section>
               Enter a name:<input id = "txtName" type = "text" onChange = {this.updateName}
               value = {this.state.userName}/>
               <button id = "btnSayhello" onClick = {this.showSayHelloMessage}>SayHello</button>
               <br/>
               user name is:{this.state.userName}    <br/>
               <div id = "SayhelloDiv">
                  <h1>{this.state.sayHelloMessage}</h1>
               </div>
            </section>
         </div>
      );
   }
}

export default App;

Una volta che entrambe le applicazioni sono in esecuzione, fare clic sul pulsante di saluto. Quindi, inserisci un nome nella casella di testo e fai clic sul pulsante sayHello. L'output sarà come indicato di seguito: