This article describes how to communicate with a gRPC-Web proxy server with the Protobuf compilation files we created from the Part 1.
1. Prerequisites
a. React Project and Protobuf files
This article will utilize the following files. They are all located in src/protos folder. Your case may be different.
greet.proto
greet_grpc_web_pb.js
greet_pb.js
b. gRPC-Web Server or Proxy
Make sure you have a gRPC-Web server or Proxy ready and reachable from your frontend app. If not accessible, please review CORS settings on your server or proxy.
2. Code Explained
This example will create hello.jsx file.
a. Define State Variable, Client, Service Request, and Service Response
The words showing inside { } for the client, service request and reply definitions are retrieved from the .js compilation files (see examples below). They are not set up arbitrarily.
greet_grpc_web_pb.js Definition of GreeterClient
greet_pb.js Definition of HelloRequest & HellpReply
b. Initiate GreeterClient
c. Define a Service-Calling Constant or Function
The request has one parameter called "name". We are setting the parameter using setName. This example will update the state varaiable retValue with the returned value from the service.
How did we know to use "setName" or "getMessage"? Those are defined in greet_pb.js file as below.
d. In the Page Component (hello.jsx)
The example below adds a h1 and a button element. The click event of the button will call the gRPC-Web service using the client and it will update the state variable retValue, which will then update h1 tag.
Below is the complete code for hello.jsx component: