Skip to content

Commit 5c67853

Browse files
scull7Luis Fernando Alvarez D
authored and
Luis Fernando Alvarez D
committedMay 23, 2019
[with-reasonml] Show both internal and shared state managment. (vercel#7312)
* Show both internal and shared state managment in example. * Add a global state custom hook.
1 parent ae8363c commit 5c67853

File tree

2 files changed

+55
-12
lines changed

2 files changed

+55
-12
lines changed
 

‎examples/with-reasonml/components/Counter.re

+28-12
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,38 @@
1-
let count = ref(0);
1+
/*
2+
This is the set of action messages which are produced by this component.
3+
* Add updates the components internal state.
4+
*/
5+
type action =
6+
| Add
7+
8+
/*
9+
This is the components internal state representation. This state object
10+
is unique to each instance of the component.
11+
*/
12+
type state = {
13+
count: int,
14+
};
15+
16+
let counterReducer = (state, action) =>
17+
switch(action) {
18+
| Add => { count: state.count + 1 }
19+
};
220

321
[@react.component]
422
let make = () => {
5-
let (_state, dispatch) = React.useReducer(
6-
(_, _) => Js.Obj.empty(),
7-
Js.Obj.empty()
8-
);
9-
10-
let countMsg = "Count: " ++ string_of_int(count^);
23+
let (state, dispatch) = React.useReducer(counterReducer, { count: 0 });
24+
let (globalState, globalDispatch) = GlobalCount.useGlobalCount();
1125

12-
let add = () => {
13-
count := count^ + 1;
14-
dispatch();
15-
};
26+
let countMsg = "Count: " ++ string_of_int(state.count);
27+
let persistentCountMsg = "Persistent Count " ++ string_of_int(globalState);
1628

1729
<div>
1830
<p> {ReasonReact.string(countMsg)} </p>
19-
<button onClick={_ => add()}> {React.string("Add")} </button>
31+
<button onClick={_ => dispatch(Add)}> {React.string("Add")} </button>
32+
<p> {ReasonReact.string(persistentCountMsg)} </p>
33+
<button onClick={_ => globalDispatch(GlobalCount.Increment)}>
34+
{React.string("Add")}
35+
</button>
2036
</div>;
2137
};
2238

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
## Global Count
3+
This captures the count globally so that it will be persisted across
4+
the `Index` and `About` pages. This replicates the functionality
5+
of the shared-modules example.
6+
*/
7+
type t = ref(int);
8+
9+
type action =
10+
| Increment;
11+
12+
let current = ref(0);
13+
14+
let increment = () => {
15+
current := current^ + 1;
16+
current;
17+
};
18+
19+
let reducer = (_state, action) => {
20+
switch(action) {
21+
| Increment =>
22+
let updated = increment();
23+
updated^
24+
}
25+
};
26+
27+
let useGlobalCount = () => React.useReducer(reducer, current^);

0 commit comments

Comments
 (0)
Please sign in to comment.