Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hooks reason graphql
{
"name": "pennyworth",
"bsc-flags": ["-bs-no-version-header", "-bs-super-errors"],
"ppx-flags": [
"./node_modules/.bin/reactjs_jsx_ppx_v3.exe",
"graphql_ppx/ppx"
],
"namespace": true,
"bs-dependencies": ["reason-react"],
"sources": [
{
"dir": "app",
"subdirs": true
},
{
"dir": "server",
"subdirs": true
}
],
"package-specs": {
"module": "es6",
"in-source": true
},
"suffix": ".bs.js",
"refmt": 3
}
module MemCache = {
type t;
[@bs.deriving abstract]
type config = {initialState: Js.Json.t};
type conf = Js.Json.t;
[@bs.module "graphql-hooks-memcache"]
external _createMemCache: config => t = "default";
};
let createMemCache = (~initialState) => {
let config = MemCache.config(~initialState);
MemCache._createMemCache(config);
};
module Client = {
type t;
[@bs.deriving abstract]
type config = {
url: string,
cache: MemCache.t,
};
[@bs.module "graphql-hooks"] [@bs.new]
external _createClient: config => t = "GraphQLClient";
};
let createClient = (~url: string, ~cache: MemCache.t) => {
let config = Client.config(~url, ~cache);
Client._createClient(config);
};
[@bs.val] [@bs.module "graphql-hooks"]
external context: React.Context.t(Client.t) = "ClientContext";
module Provider = {
let provider = React.Context.provider(context);
[@react.component] [@bs.module "graphql-hooks"] [@bs.scope "ClientContext"]
external make: (~value: Client.t, ~children: React.element) => React.element =
"Provider";
};
[@bs.deriving abstract]
type clientRequestResult('any) = {
loading: bool,
cacheHit: bool,
error: bool,
data: 'any,
};
type queryResponse('a) =
| Loading
| Error(string)
| Data('a);
[@bs.module "graphql-hooks"]
external _useQuery: string => clientRequestResult('any) = "useQuery";
let useQuery = (~query) => {
let result = _useQuery(query##query);
switch (result->loadingGet, result->errorGet, result->dataGet) {
| (true, _, _) => Loading
| (false, false, Some(response)) => Data(response |> query##parse)
| _ => Error("something is wrong")
};
};
[@bs.config {jsx: 3}];
module SayHelloQuery = [%graphql {|
{
sayHello
}
|}];
let query = SayHelloQuery.make();
[@react.component]
let make = () => {
let result = GraphqlHooks.useQuery(~query);
let queryResult =
switch (result) {
| Loading => <div> {ReasonReact.string("Loading")} </div>
| Error(message) => <div> {ReasonReact.string(message)} </div>
| Data(response) => <div> {ReasonReact.string(response##sayHello)} </div>
};
<>
<div> {ReasonReact.string("HELLO")} </div>
queryResult
</>;
};
deps:
"graphql-hooks": "^3.4.1",
"graphql-hooks-memcache": "^1.2.0",
devDeps:
"graphql_ppx": "^0.2.8",
"reason-react": "git://github.com/sync/reason-react.git#hooks"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment