Git Product home page Git Product logo

rescript-recoil's Introduction

rescript-recoil

Node.js CI

Zero-cost bindings to Facebook's Recoil library

โš ๏ธ These bindings are still in experimental stages, use with caution

Installation

Run the following command:

$ yarn add recoil rescript-recoil

Then add rescript-recoil to your bsconfig.json's dependencies:

 {
   "bs-dependencies": [
+    "rescript-recoil"
   ]
 }

Usage

Atom

let textState = Recoil.atom({
  key: "textState",
  default: "",
})

Selector

A nice feature the OCaml type-system enables is the ability to differenciate Recoil values between the ones that can only read state with the ones that can write state. This way, you can't use hooks with write capabilities with a read-only value.

With read only capabilities

let textStateSize = Recoil.selector({
  key: "textStateSize",
  get: ({get}) => {
    let textState = get(textState)
    Js.String.length(textState)
  },
})

With write capabilities

let textStateSize = Recoil.selectorWithWrite({
  key: "textStateSize",
  get: ({get}) => {
    let textState = get(textState);
    Js.String.length(textState);
  },
  set: ({set}, newSize) => {
    let currentTextState = get(textState);
    set(textState, currentTextState->Js.String.slice(~from=0, ~to_=newSize));
  }
});

Async

let user = Recoil.asyncSelector({
  key: "user",
  get: ({get}) => {
    fetchUser(get(currentUserId))
  },
})

Hooks

useRecoilState

let (state, setState) = Recoil.useRecoilState(textState);

state // read
setState(textState => newTextState) // write

useRecoilValue

let state = Recoil.useRecoilValue(textState)

state // read

useSetRecoilState

let setState = Recoil.useSetRecoilState(textState)

setState(textState => newTextState) // write

useResetRecoilState

let reset = Recoil.useResetRecoilState(textState)

reset() // write

useRecoilCallback

  • Dependency free (reevaluates the callback at every render): useRecoilCallback(...)
  • Zero-dependency (never reevaluates the callback): useRecoilCallback0(...)
  • One-dependency (reevaluates when dep changes): useRecoilCallback1(..., [|dep|])
  • Multiple-dependencies: useRecoilCallback2(..., (dep1, dep2)) (goes from 2 to 5)
let onClick = Recoil.useRecoilCallback(({snapshot: {getPromise}}, event) => {
  let _ = getPromise(myAtom)
    |> Js.Promise.then_(value => {
      Js.log(value)
      Js.Promise.resolve()
    })
})

<button onClick={onClick}>
  {"Click me"->React.string}
</button>

useRecoilValueLoadable

let loadable = Recoil.useRecoilValueLoadable(textState)

Js.log(loadable->Recoil.Loadable.state)
Js.log(loadable->Recoil.Loadable.getValue)

Examples

The Recoil Basic Tutorial has been made in ReasonReact: check the source!

You can run it using:

$ yarn examples

and going to http://localhost:8000/TodoList.html

Memoization

type t = {
  id: string,
  value: string,
  isCompleted: bool,
}

// For atoms
let todoItemFamily = Recoil.atomFamily({
  key: "todo",
  default: param => {
    id: param,
    value: "",
    isCompleted: false,
  },
})

// For selectors
let todoItemLengthFamily = Recoil.selectorFamily({
  key: "todo",
  // The `Fn` wrapper is needed here so that BuckleScript
  // outputs the correct value
  get: param => Fn(({get}) => {
    get(todoItemFamily(param)).value->Js.String2.length
  }),
})

And use it within a React component:

[@react.component]
let make = (~todoId) => {
  let (todo, setTodo) = Recoil.useRecoilState(todoItemFamily(id))

  // ...
  <>
    {todo.value->React.string}
  </>
}

rescript-recoil's People

Contributors

anmonteiro avatar barodeur avatar bloodyowl avatar dependabot[bot] avatar happylinks avatar nireno avatar ryyppy avatar searleser97 avatar tatchi avatar yawaramin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

rescript-recoil's Issues

Applications under the /examples does not work because of "module": "es6"

Reproduction steps

  1. yarn install
  2. yarn build
  3. yarn examples
  4. Open http://localhost:8000/Async.html (or any other html files) in the browser
  5. Get /TodoList.bs:3 Uncaught SyntaxError: Cannot use import statement outside a module in the browser console

FYI

If I change "module": "es6" in the bsconfig.json to "module": "commonjs", It works well. I think that it would be nice if the /examples was separated to the other repository or other package.

Value equality in selectors?

Hi, it seems that selectors will always cause a rerender if the reference changed (even though the value stays the same). Is there a way to use value equality instead?

Thanks!

dangerouslyAllowMutability binding

Hey!

I needed the dangerouslyAllowMutability binding for something, any interest to have a PR for it?

type atomWithDangerouslyAllowMutabilityConfig('value) = {
  key: string,
  default: 'value,
  dangerouslyAllowMutability: bool,
};

[@bs.module "recoil"]
external atomWithDangerouslyAllowMutability:
  atomWithDangerouslyAllowMutabilityConfig('value) =>
  Recoil.readWrite('value) =
  "atom";

Not sure if this is the nicest API for it, and I don't think a lot of people will need it, but thought I'd ask :)

not working with rescript-react

migrated from reason-react to rescript-react and I get errors like this:

It's possible that your build is stale.
Try to clean the artifacts and build again?

Here's the original error message
The files /code/sobras/node_modules/rescript-recoil/lib/ocaml/recoil.cmi
and /code/sobras/node_modules/@rescript/react/lib/ocaml/react.cmi
make inconsistent assumptions over interface React

The value `atomWithDangerouslyAllowMutability` can't be found in Recoil

I haven't been able to use atomWithDangerouslyAllowMutability from Recoil

image

and alternative is to use it from Recoil__Atom which does not throw errors there, but it throws when trying to use useRecoilValue hooks.

image

I believe it has to do with the PR #29, where it was forgotten to update the interface file as well (Recoil.resi)

Actually, after deleting the interface file it works correctly

Atom Effect onSet

Hey there,

I'm having issues using onSet((~newValue, ~oldValue) => { Js.log(newValue)});
Could it be that the binding is wrong?

onSet: (~newValue: 'value, ~oldValue: 'value) => unit,

I think it should be onSet: ((~newValue: 'value, ~oldValue: 'value) => unit) => unit,?

I can make a PR but wanted to check first if I might be doing something wrong.

Add support for helpers

  • waitForAll
  • waitForAny
  • waitForNone
  • noWait
  • constSelector we don't seem to need it with Reason
  • errorSelector we don't seem to need it with Reason

How to use asyncSelectorFamily?

I think, according to docs it should be

let selectorFamily = Recoil.asyncSelectorFamily({
    key: "theKey",
    get: (arg) => ({get}) => Js.Promise.resolve("value derived from arg"),
  });

But it does no compile:

Error: This function expects too many arguments, it should have type
'a => Recoil.fn(Recoil.getValue(Js.Promise.t('b)))

Dealing with `DefaultValue`

As I had the opportunity to say in my recent pull request #32: Thanks for this really nice binding. IMO the Recoil API types are particularly complex and those bindings really helps ๐Ÿ™


My question is regarding this special type DefaultValue that Recoil has and that appear to be ignored from this binding.
It's used in some some callbacks instead of passing a value.

For example the set callback of a selector can either receive a value or an instance of DefaultValue. DefaultValue is passed to the callback when the action dispatch is a reset instead of setting a new value.

From recoil doc:

function selector<T>({
  key: string,

  get: ({
    get: GetRecoilValue,
    getCallback: GetCallback,
  }) => T | Promise<T> | RecoilValue<T>,

  set?: (
    {
      get: GetRecoilValue,
      set: SetRecoilState,
      reset: ResetRecoilState,
    },
    newValue: T | DefaultValue,
  ) => void,

  dangerouslyAllowMutability?: boolean,

  cachePolicy_UNSTABLE?: CachePolicy,
})

Note that SetRecoilState can also be used to set a value to a DefaultValue instance.

The common pattern to handle this special value in javascript is the following:

import { atom, selector, DefaultValue } from "recoil" 

const atom = atom({ key: "Atom", default: 1 })
const plusOne = selector({
  key: "AtomPlusOne",
  get: ({ get }) => get(atom) + 1,
  set: ({ set }, newValue) =>
    newValue instanceof DefaultValue
      ? set(atom, newValue) // forward the reset action
      : set(atom, newValue - 1)
})

Because of this T | DefaultValue type, it seems difficult to create a zero-cost binding that handle the DefaultValue separately using maybe a rescript variant type.

I'm pretty new rescript binding, but I was thinking that if the library would use a type like the one bellow, it would make handling the default value slightly simpler.

module PossiblyDefaultValue = {
  @unboxed
  type t<'value> = PossiblyDefaultValue('value)

  type defaultValue
  @module("recoil") external defaultValue_: defaultValue = "DefaultValue"

  let defaultValue = defaultValue_

  @warning("-27")
  let isDefaultValue: t<'value> => bool = action => %raw("action instanceof defaultValue")
}

Personally, I would probably prefer a "low-cost" binding that would use a proper variant like option<'value>, or a new custom variant type, but at least I think that my suggestion above could provide the building bricks to build my own low-cost variant.

Do you think @bloodyowl that is is worth considering adding such a PossiblyDefaultValue.t<'value> type? I'll be more than happy to make this my second contribution to the bindings. If you decide to keep the types as they are, I would also be happy to just write down a "Dealing with DefaultValue" section to the readme.

Initializing an atom with empty arrow throws an error

Trying to initialize this array

let cartItems =
  Recoil.atom({key: "cartItems", default: [||]});

I get the following error from the compiler

let cartItems =
[0]   13 โ”‚   Recoil.atom({key: "cartItems", default: [||]});
[0]   14 โ”‚ 
[0]   
[0]   This expression's type contains type variables that can't be generalized:
[0]   Recoil.readWrite(array('_weak1))
[0]   
[0]   This happens when the type system senses there's a mutation/side-effect,
[0]   in combination with a polymorphic value.
[0]   Using or annotating that value usually solves it. More info:
[0]   https://realworldocaml.org/v1/en/html/imperative-programming-1.html#side-effects-and-weak-polymorphism

If I initialize it with an item, then the error disappears.

let cartItems =
  Recoil.atom({key: "cartItems", default: [| { id: 1, name: "" } |]});

Any idea what's going on or how to add the type to recoil?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.