Skip to content
This repository has been archived by the owner on Jan 31, 2023. It is now read-only.

A simple hook for sane promise handling in ReasonReact

Notifications You must be signed in to change notification settings

rescriptbr/reason-async-hook

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

All Contributors


InstallationUsageHow does it work



Usage

[@react.component]
let make = () => {
  let (AsyncHook.{state: createUserState}, createUser) = AsyncHook.use((~cb, ~name, ~age) => cb(() => {
    // It accepts anything that returns a Promise.t(result('a, 'e))
    fetch("/user", ~params={
      name,
      age,
    })
  }));

  let onSubmit= () => {
    createUser(~name=form.values.name, ~age=form.values.age)
    // Handle the result after the call
    |> Promise.tapError(error => {
      Js.log(error)
    })
    |> Promise.getOk(result => {
      Js.log("Success!")
    })
  };

  // or use the declarative mode
  <div>
    {
      switch(createUserState) {
        | Idle => <button onClick={_ => onSubmit()}>"Create user"->React.string</button>
        | Loading => <p>{"Loading..."->React.string}</p>
        | Error(error) => 
          <p>
            "User created with id #"->React.string
            {data.user.id->React.string}
          </p>
        | Data(data) =>
          <p>
            "User created with id #"->React.string
            {data.user.id->React.string}
          </p>
      }
    }
  </div>
}

Installation

yarn add reason-async-hook reason-promise

bsconfig.json

  "bs-dependencies": [
    "reason-async-hook",
    "reason-promise"
  ]

Promises are better with reason-promise!

How does it work

We just leverage ReasonML currying and awesome type inference. reason-promise runs on top of JavaScript promises but it adds more functionality to them, and the one we want is the result type one, allowing for fine-grained control over the call and railway programming.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Gabriel Rubens

💻 🤔 📖

Marcos Oliveira

📖 🎨

Guilherme de Andrade

📖

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

About

A simple hook for sane promise handling in ReasonReact

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages