Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/bloodyowl/rescript-react-update
useReducer with updates and side effects!
https://github.com/bloodyowl/rescript-react-update
react reason-react reasonml side-effects update
Last synced: about 2 months ago
JSON representation
useReducer with updates and side effects!
- Host: GitHub
- URL: https://github.com/bloodyowl/rescript-react-update
- Owner: bloodyowl
- License: mit
- Created: 2019-04-18T16:53:57.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2023-08-18T16:10:18.000Z (11 months ago)
- Last Synced: 2024-05-08T05:34:02.290Z (about 2 months ago)
- Topics: react, reason-react, reasonml, side-effects, update
- Language: ReScript
- Size: 143 KB
- Stars: 95
- Watchers: 5
- Forks: 9
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- Funding: .github/FUNDING.yml
- License: MIT-LICENSE
Lists
- awesome-list - rescript-react-update
README
# rescript-react-update
> useReducer with updates and side effects!
## Installation
```console
$ yarn add rescript-react-update
```or
```console
$ npm install --save rescript-react-update
```Then add `rescript-react-update` to your `bsconfig.json` `bs-dependencies` field.
## ReactUpdate.useReducer
```reason
type state = int;type action =
| Increment
| Decrement;[@react.component]
let make = () => {
let (state, send) =
ReactUpdate.useReducer((state, action) =>
switch (action) {
| Increment => Update(state + 1)
| Decrement => Update(state - 1)
},
0
);
;
{state->React.int}
send(Decrement)}> {"-"->React.string}
send(Increment)}> {"+"->React.string}
};
```### Lazy initialisation
## ReactUpdate.useReducerWithMapState
If you'd rather initialize state lazily (if there's some computation you don't want executed at every render for instance), use `useReducerWithMapState` where the first argument is a function taking `unit` and returning the initial state.
```reason
type state = int;type action =
| Increment
| Decrement;[@react.component]
let make = () => {
let (state, send) =
ReactUpdate.useReducerWithMapState(
(state, action) =>
switch (action) {
| Increment => Update(state + 1)
| Decrement => Update(state + 1)
},
() => 0
);
;
{state->React.int}
send(Decrement)}> {"-"->React.string}
send(Increment)}> {"+"->React.string}
};
```### Cancelling a side effect
The callback you pass to `SideEffects` & `UpdateWithSideEffect` returns an `option(unit => unit)`, which is the cancellation function.
```reason
// doesn't cancel
SideEffects(({send}) => {
Js.log(1);
None
});
// cancels
SideEffects(({send}) => {
let request = Request.make();
request->Future.get(payload => send(Receive(payload)))
Some(() => {
Request.cancel(request)
})
});
```If you want to copy/paste old reducers that don't support cancellation, you can use `ReactUpdateLegacy` instead in place of `ReactUpdate`. Its `SideEffects` and `UpdateWithSideEffects` functions accept functions that return `unit`.