atom.io/react
package contents
Exports | Description |
---|---|
useI | Update a reactive variable. |
useO | Observe a reactive variable. |
useJSON | Observe the JSON form of a mutable atom. |
useTL | Control a timeline and observe its state. |
useO
useO
is a React hook that allows you to observe reactive variables in your React components.
import { atom } from "atom.io"
import { useO } from "atom.io/react"
function discoverUrl() {
return new URL(window.location.href)
}
const urlState = atom<string>({
key: `url`,
default: () => discoverUrl().toString(),
effects: [
({ setSelf }) => {
window.addEventListener(`popstate`, () => {
setSelf(discoverUrl().toString())
})
},
],
})
export const UrlDisplay: React.FC = () => {
const url = useO(urlState)
return <div>{url}</div>
}
useI
useI
is a React hook that allows you to update reactive variables in your React components.
import { atom } from "atom.io"
import { useI, useO } from "atom.io/react"
const toggleState = atom<boolean>({
key: `toggle`,
default: false,
})
export const UrlDisplay: React.FC = () => {
const setToggle = useI(toggleState)
const toggle = useO(toggleState)
return (
<input
type="checkbox"
checked={toggle}
onChange={() => {
setToggle((t) => !t)
}}
/>
)
}
useJSON
useJSON
is a React hook that makes working with mutable atoms in your react components more convenient.
import { atom } from "atom.io"
import { useJSON } from "atom.io/react"
import { SetRTX } from "atom.io/transceivers/set-rtx"
const numbersCollectionState = atom<SetRTX<number>, number[]>({
key: `numbersCollection::mutable`,
mutable: true,
default: () => new SetRTX([0]),
toJson: (s) => [...s],
fromJson: (a) => new SetRTX(a),
})
export const Numbers: React.FC = () => {
const numbers = useJSON(numbersCollectionState)
return (
<>
{numbers.map((n) => (
<div key={n}>{n}</div>
))}
</>
)
}
useTL
useTL
provides convenient access to the undo
and redo
utilities, as well as metadata representing how many events are on the timeline (length
) and where the timeline is currently positioned (at
).
import { useTL } from "atom.io/react"
import { coordinatesTL } from "../core/timeline/create-a-timeline"
export const UrlDisplay: React.FC = () => {
const { at, length, undo, redo } = useTL(coordinatesTL)
return (
<>
<div>{at}</div>
<div>{length}</div>
<button type="button" onClick={undo}>
undo
</button>
<button type="button" onClick={redo}>
redo
</button>
</>
)
}