4.1.1 • Published 4 years ago

@echo-health/react-grpc v4.1.1

Weekly downloads
18
License
-
Repository
-
Last release
4 years ago

react-grpc

This package provides some helpers and tools to use gRPC via simple Rook hooks. This is to be used in combination with protoc and ts-protoc-gen.

For example, if you specify a service like this in your proto file:

message ListAnimalsRequest {
  string search_term: 1;
}

message ListAnimalsResponse {
  repeated string animals = 1;
}

service Animals {
  rpc ListAnimals(ListAnimalsRequest) returns (ListAnimalsResponse) {}
}

This plugin will generate hooks allowing you to do:

const { data, isLoading, error } = useListAnimals({ searchTerm: props.searchTerm });

Generating the code

To generate the right code, first install the necessary protoc plugins. These need to be installed globally so they can be used by protoc.

npm install -g ts-protoc-gen @echo-health/react-grpc

Next, specify where you want your clients to be outputted. All three (ts, js and react) must be outputted in the same directory in order to work.

protoc -I . myservice.proto \
  --js_out=import_style=commonjs,binary:clients/js \
  --react_out=clients/js \
  --ts_out=service=true:clients/js

This will create a file called myservice-react.js and matching type definitions in myservice-react.d.ts.

React app setup

In order to be able to use any of the generate hooks within your application there is some required setup.

First, install react-grpc in your react app.

npm install @echo-health/react-grpc

Then, wrap your app in the GrpcProvider:

import React from "react";
import ReactDOM from "react-dom";
+ import { GrpcProvider } from "@echo-health/react-grpc";

 ReactDOM.render(
   <StoreContext.Provider value={store}>
+    <GrpcProvider host={"https://your-grpc-service-gateway.com}>
       <App />
+    </GrpcProvider>,
   document.getElementById("root")
 );

If you need to provide any meta data for each gRPC request (for auth for example) you can also specify a prop called getMetadata on the GrpcProvider. It should follow the following signature:

interface GrpcProviderMetadata {
    [k: string]: string;
}

interface GrpcProviderContext {
    host: string;
    getMetadata?: () => GrpcProviderMetadata | Promise<GrpcProviderMetadata>;
}

You can now use your generated hooks in your app :tada:

TO-DO

  • Add more documentation on each of the return values of the hooks.
  • Add contributing documentation (how to use a local copy of this to work on it)