All Projects → reasonml-community → Reason Apollo Hooks

reasonml-community / Reason Apollo Hooks

Licence: mit
Deprecated in favor of https://github.com/reasonml-community/graphql-ppx

Programming Languages

reason
219 projects

Projects that are alternatives of or similar to Reason Apollo Hooks

Learn Graphql
Real world GraphQL tutorials for frontend developers with deadlines!
Stars: ✭ 586 (+318.57%)
Mutual labels:  graphql, apollo, reasonml
Livepeerjs
JavaScript tools and applications that interact with Livepeer's smart contracts and peer-to-peer network
Stars: ✭ 116 (-17.14%)
Mutual labels:  graphql, apollo
Create Apollo App
Create Apollo App is a command-line tool designed to generate fully-configured starter Apollo GraphQL projects with essential dependencies for developing web, server and mobile applications and zero build configuration.
Stars: ✭ 110 (-21.43%)
Mutual labels:  graphql, apollo
Goofi
✨Let's contribute to OSS. Here is how to find good first issues in GitHub. "goofi" is an abbreviation of "good first issues".
Stars: ✭ 125 (-10.71%)
Mutual labels:  graphql, apollo
Meteor Integration
🚀 meteor add apollo
Stars: ✭ 107 (-23.57%)
Mutual labels:  graphql, apollo
Thorium
Platform for starship simulator controls
Stars: ✭ 109 (-22.14%)
Mutual labels:  graphql, apollo
React Graphql Github Apollo
🚀 A React + Apollo + GraphQL GitHub Client. Your opportunity to learn about these technologies in a real world application.
Stars: ✭ 1,563 (+1016.43%)
Mutual labels:  graphql, apollo
Booben
Web app constructor based on React, with GraphQL bindings
Stars: ✭ 96 (-31.43%)
Mutual labels:  graphql, apollo
React Redux Graphql Apollo Bootstrap Webpack Starter
react js + redux + graphQL + Apollo + react router + hot reload + devTools + bootstrap + webpack starter
Stars: ✭ 127 (-9.29%)
Mutual labels:  graphql, apollo
Apollo Universal Starter Kit
Apollo Universal Starter Kit is an SEO-friendly, fully-configured, modular starter application that helps developers to streamline web, server, and mobile development with cutting-edge technologies and ultimate code reuse.
Stars: ✭ 1,645 (+1075%)
Mutual labels:  graphql, apollo
Join Monster Graphql Tools Adapter
Use Join Monster to fetch your data with Apollo Server.
Stars: ✭ 130 (-7.14%)
Mutual labels:  graphql, apollo
Guide
📖 The GraphQL Guide website
Stars: ✭ 104 (-25.71%)
Mutual labels:  graphql, apollo
Leo
Highly Extensible, Declarative Static Site Generator
Stars: ✭ 100 (-28.57%)
Mutual labels:  graphql, apollo
Apollo Link
🔗 Interface for fetching and modifying control flow of GraphQL requests
Stars: ✭ 1,434 (+924.29%)
Mutual labels:  graphql, apollo
React Fullstack Graphql
Starter projects for fullstack applications based on React & GraphQL.
Stars: ✭ 1,352 (+865.71%)
Mutual labels:  graphql, apollo
Universal React Apollo Example
Universal React Apollo App (GraphQL) consuming: https://github.com/WeLikeGraphQL/wordpress-graphql-api-example!
Stars: ✭ 117 (-16.43%)
Mutual labels:  graphql, apollo
Reason Graphql
GraphQL server in pure Reason (Bucklescript)
Stars: ✭ 137 (-2.14%)
Mutual labels:  graphql, reasonml
Meteor Apollo Starter Kit
Meteor, Apollo, React, PWA, Styled-Components boilerplate
Stars: ✭ 91 (-35%)
Mutual labels:  graphql, apollo
Angular Fullstack Graphql
🚀 Starter projects for fullstack applications based on Angular & GraphQL.
Stars: ✭ 92 (-34.29%)
Mutual labels:  graphql, apollo
Awesome Apollo Graphql
A curated list of amazingly awesome things regarding Apollo GraphQL ecosystem 🌟
Stars: ✭ 126 (-10%)
Mutual labels:  graphql, apollo

⚠️ Prefer the new https://github.com/reasonml-community/reason-apollo-client instead


reason-apollo-hooks

All Contributors

Reason bindings for the official @apollo/react-hooks

Table of contents

Installation ⬆️

yarn add reason-apollo-hooks [email protected] @apollo/react-hooks

BuckleScript <= 5.0.0

yarn add [email protected] [email protected] @apollo/react-hooks

Follow the installation instructions of graphql_ppx_re.

Then update your bsconfig.json

"bs-dependencies": [
  ...
+ "reason-apollo-hooks",
+ "reason-apollo"
]

Setting up ⬆️

Add the provider in the top of the tree

/* Create an InMemoryCache */
let inMemoryCache = ApolloInMemoryCache.createInMemoryCache();

/* Create an HTTP Link */
let httpLink =
  ApolloLinks.createHttpLink(~uri="http://localhost:3010/graphql", ());

let client =
  ReasonApollo.createApolloClient(~link=httpLink, ~cache=inMemoryCache, ());

let app =
 <ApolloHooks.Provider client>
   ...
 </ApolloHooks.Provider>

Usage with reason-apollo ⬆️

To use with reason-apollo's ReasonApollo.Provider already present in your project:

let client = ... // create Apollo client

ReactDOMRe.renderToElementWithId(
  <ReasonApollo.Provider client>
    <ApolloHooks.Provider client>
      <App />
    </ApolloHooks.Provider>
  </ReasonApollo.Provider>,
  "root",
);

Available hooks ⬆️

useQuery ⬆️

open ApolloHooks

module UserQuery = [%graphql {|
  query UserQuery {
    currentUser {
      name
    }
  }
|}];

[@react.component]
let make = () => {
  /* Both variant and records available */
  let (simple, _full) = useQuery(UserQuery.definition);

  <div>
  {
    switch(simple) {
      | Loading => <p>{React.string("Loading...")}</p>
      | Data(data) =>
        <p>{React.string(data##currentUser##name)}</p>
      | NoData
      | Error(_) => <p>{React.string("Get off my lawn!")}</p>
    }
  }
  </div>
}

Using the full record for more advanced cases

[@react.component]
let make = () => {
  /* Both variant and records available */
  let (_simple, full) = useQuery(UserQuery.definition);

  <div>
  {
    switch(full) {
      | { loading: true }=> <p>{React.string("Loading...")}</p>
      | { data: Some(data) } =>
        <p>{React.string(data##currentUser##name)}</p>
      | any other possibilities =>
      | { error: Some(_) } => <p>{React.string("Get off my lawn!")}</p>
    }
  }
  </div>
}

Using fetchPolicy to change interactions with the apollo cache, see apollo docs.

let (_simple, full) = useQuery(~fetchPolicy=NetworkOnly, UserQuery.definition);

Using errorPolicy to change how errors are handled, see apollo docs.

let (simple, _full) = useQuery(~errorPolicy=All, UserQuery.definition);

Using skip to skip query entirely, see apollo docs.

let (simple, _full) =
  useQuery(
    ~skip=
      switch (value) {
      | None => true
      | _ => false
      },
    UserQuery.definition,
  );

useMutation ⬆️

module ScreamMutation = [%graphql {|
  mutation ScreamMutation($screamLevel: Int!) {
    scream(level: $screamLevel) {
      error
    }
  }
|}];

[@react.component]
let make = () => {
  /* Both variant and records available */
  let ( screamMutation, simple, _full ) =
    useMutation(~variables=ScreamMutation.makeVariables(~screamLevel=10, ()), ScreamMutation.definition);
  let scream = (_) => {
    screamMutation()
      |> Js.Promise.then_(((simple, _full)) => {
           // Trigger side effects by chaining the promise returned by screamMutation()
           switch (simple) {
             // You *must* set the error policy to be able to handle errors
             // in then_. See EditPersons.re for more
           | ApolloHooks.Mutation.Errors(_theErrors) => Js.log("OH NO!")
           | NoData => Js.log("NO DATA?")
           | Data(_theData) => Js.log("DATA!")
           };
           Js.Promise.resolve();
         })
      |> ignore
  }

  // Use simple (and/or full) for (most) UI feedback
  <div>
    {switch (simple) {
     | NotCalled
     | Data(_) => React.null
     | Loading => <div> "Screaming!"->React.string </div>
     | NoData
     | Error(_) => <div> "Something went wrong!"->React.string </div>
     }}
    <button onClick={scream} disabled={simple === Loading}>
      {React.string("You kids get off my lawn!")}
    </button>
  </div>
}

If you don't know the value of the variables yet you can pass them in later

[@react.component]
let make = () => {
  /* Both variant and records available */
  let ( screamMutation, _simple, _full ) = useMutation(ScreamMutation.definition);
  let scream = (_) => {
    screamMutation(~variables=ScreamMutation.makeVariables(~screamLevel=10, ()), ())
      |> Js.Promise.then_(((simple, _full)) => {
           ...
         })
      |> ignore
  }

  <div>
    <button onClick={scream}>
      {React.string("You kids get off my lawn!")}
    </button>
  </div>
}

useSubscription ⬆️

In order to use subscriptions, you first need to set up your websocket link:

/* Create an InMemoryCache */
let inMemoryCache = ApolloInMemoryCache.createInMemoryCache();

/* Create an HTTP Link */
let httpLink =
  ApolloLinks.createHttpLink(~uri="http://localhost:3010/graphql", ());
+
+/* Create a WS Link */
+let webSocketLink =
+  ApolloLinks.webSocketLink({
+    uri: "wss://localhost:3010/graphql",
+    options: {
+      reconnect: true,
+      connectionParams: None,
+    },
+  });
+
+/* Using the ability to split links, you can send data to each link
+   depending on what kind of operation is being sent */
+let link =
+  ApolloLinks.split(
+    operation => {
+      let operationDefition =
+        ApolloUtilities.getMainDefinition(operation.query);
+      operationDefition.kind == "OperationDefinition"
+      && operationDefition.operation == "subscription";
+    },
+    webSocketLink,
+    httpLink,
+  );

let client =
-  ReasonApollo.createApolloClient(~link=httpLink, ~cache=inMemoryCache, ());
+  ReasonApollo.createApolloClient(~link, ~cache=inMemoryCache, ());

let app =
 <ApolloHooks.Provider client>
   ...
 </ApolloHooks.Provider>

Then, you can implement useSubscription in a similar manner to useQuery

module UserAdded = [%graphql {|
  subscription userAdded {
    userAdded {
      id
      name
    }
  }
|}];


[@react.component]
let make = () => {
  let (userAddedSubscription, _full) = ApolloHooks.useSubscription(UserAdded.definition);

  switch (userAddedSubscription) {
    | Loading => <div> {ReasonReact.string("Loading")} </div>
    | Error(error) => <div> {ReasonReact.string(error##message)} </div>
    | Data(_response) =>
      <audio autoPlay=true>
      <source src="notification.ogg" type_="audio/ogg" />
      <source src="notification.mp3" type_="audio/mpeg" />
    </audio>
  };
};

Cache ⬆️

There are a couple of caveats with manual cache updates.

TL;DR

  1. If you need to remove items from cached data, it is enough to just filter them out and save the result into cache as is.
  2. If you need to add the result of a mutation to a list of items with the same shape, you simply concat it with the list and save into cache as it.
  3. When you need to update a field, you have to resort to raw javascript to use spread operator on Js.t object in order to preserve __typename that apollo adds to all queries by default.

An example of cache update could look like this:

module PersonsQuery = [%graphql
{|
  query getAllPersons  {
    allPersons  {
      id
      age
      name
    }
  }
|}
];

module PersonsReadQuery = ApolloClient.ReadQuery(PersonsQuery);
module PersonsWriteQuery = ApolloClient.WriteQuery(PersonsQuery);

external cast: Js.Json.t => PersonsQuery.t = "%identity";

let updatePersons = (~client, ~name, ~age) => {
  let query = PersonsQuery.make();
  let readQueryOptions = ApolloHooks.Utils.toReadQueryOptions(query);

  // can throw exception of cache is empty
  switch (PersonsReadQuery.readQuery(client, readQueryOptions)) {
  | exception _ => ()
  | cachedResponse =>
    switch (cachedResponse |> Js.Nullable.toOption) {
    | None => ()
    | Some(cachedPersons) =>
      // readQuery will return unparsed data with __typename field, need to cast it since
      // it has type Json.t, but we know it will have the same type as PersonsReadQuery.t
      let persons = cast(cachedPersons);

      // to remove items, simply filter them out
      let updatedPersons = {
        "allPersons":
          Belt.Array.keep(persons##allPersons, person => person##age !== age),
      };

      // when updating items, __typename must be preserved, but since it is not a record,
      // can't use spread, so use JS to update items
      let updatedPersons = {
        "allPersons":
          Belt.Array.map(persons##allPersons, person =>
            person##name === name ? [%bs.raw {| {...person, age } |}] : person
          ),
      };

      PersonsWriteQuery.make(
        ~client,
        ~variables=query##variables,
        ~data=updatedPersons,
        (),
      );
    }
  };
};

reason-apollo-hooks parses response data from a query or mutation using parse function created by graphql_ppx. For example, when using @bsRecord directive, the response object will be parsed from a Js.t object to a reason record. In this case, the response data in reason code is not the same object that is stored in cache, since react-apollo saves data in cache before it is parsed and returned to the component. However, when updating cache, the data must be in the same format or apollo cache won't work correctly and throw errors.

If using directives like @bsRecord, @bsDecoder or @bsVariant in graphql_ppx, the data needs to be serialized back to JS object before it is written in cache. Since there is currently no way to serialize this data (see this issue in graphql_ppx), queries that will be updated in cache shouldn't use any of those directive, unless you will take care of the serialization yourself.

By default, apollo will add field __typename to the queries and will use it to normalize data and manipulate cache (see normalization). This field won't exist on parsed reason objects, since it is not included in the actual query you write, but is added by apollo before sending the query. Since __typename is crucial for the cache to work correctly, we need to read data from cache in its raw unparsed format, which is achieved with readQuery from ApolloClient.ReadQuery defined in reason-apollo.

Fragment ⬆️

Using fragments.

Fragments can be defined and used like this:

// Fragments.re
module PersonFragment = [%graphql
  {|
  fragment person on Person {
      id
      name
      age
  }
|}
];

module PersonsQuery = [%graphql
{|
  query getAllPersons  {
    ...Fragments.PersonFragment.Person
  }
|}
];

See examples/persons/src/fragments/LoadMoreFragments.re.

Getting it running

yarn
yarn start

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Gabriel Rubens

💻 📖 🤔

Ariel Schiavoni

📖

Matt

💻

Tomasz Cichocinski

🐛 💻

Thibaut Mattio

💻

Emilio Srougo

🐛

Mike Anderson

💻

Yuri Jean Fabris

💻

Margarita Krutikova

💻 👀 🤔

Kyrylo Yakymenko

🐛 💻

Lukas Hambsch

🐛

Jaap Frolich

💻 👀 🤔

Rickard Laurin

🐛

Medson Oliveira

💻 👀 🤔

soulplant

💻

mbirkegaard

💻

Dragoș Străinu

📖

Brad Dunn

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].