Bindings for the Jotai library
The bindings aim to be as close as possible to the original API, and introduces only a little runtime code only when absolutely necessary (see the derived atom sections below).
The main Provider "wrapper" for the whole application
module App = {
@react.component
let make = () =>
<Jotai.Provider>
...
</Jotai.Provider>
}
Unlike the original API, and in order to keep the flexibility, derived atoms requires some light runtime code and small changes to the semantic: get
is now getter
(see derivedAtom
and derivedAsyncAtom
for more).
// Inside a derived atom
let value = getter->Jotai.Atom.get(atom)
Unlike the original API, and in order to keep the flexibility, writable derived atoms requires some light runtime code and small changes to the semantic: set
is now setter
(see makeWritableDerived
for more).
// Inside a writable derived atom
setter->Jotai.Atom.set(atom, newValue)
Creates a simple readable/writable atom:
let counterAtom = Jotai.Atom.make(10)
Creates a derived (readonly) atom.
let doubleCounterDerivedAtom = Jotai.Atom.makeDerived(getter => getter->Jotai.Atom.get(counterAtom) * 2)
Creates an async derived (readonly) atom.
let asyncDerivedAtom = Jotai.Atom.makeAsyncDerived(getter =>
Js.Promise.make((~resolve, ~reject as _) => {
let tripleCounter = getter->Jotai.Atom.get(counterAtom) * 3
Js.Global.setTimeout(() => resolve(. tripleCounter), 300)->ignore
})
)
In the following example we re-use an existing readable and writable atom and derive both a new getter and a new setter.
let writableDerivedCounter = Atom.makeWritableDerived(
getter => getter->Atom.get(counterAtom) * 2,
(getter, setter, arg) => {
let newCounterValue = getter->Atom.get(counterAtom) * 2 + arg
setter->Atom.set(counterAtom, newCounterValue)
},
)
To prevent any mistake you can't use this hook with readonly derived atom
let (counter, setCounter) = Jotai.Hooks.use(counterAtom)
Can be used only with readable atoms. Returns only the value, no setter
let doubleCounter = Jotai.Hook.useReadable(doubleCounterDerivedAtom)
Can be used only with readable atoms. Returns only the value, no setter.
In the example below tripleCounter
is not a Promise, but the component must be wrapped
in a React Suspense
component.
let tripleCounter = Jotai.Hook.useReadable(asyncDerivedAtom)
Can be used only with writable atoms. Returns only the setter, no value
let setCounter = Jotai.Hook.useWritable(counterAtom)
You can check the tests for more.
Some functions are still missing, namely: