Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show both internal and shared state managment in example. #7312

Merged
merged 13 commits into from
May 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 28 additions & 12 deletions examples/with-reasonml/components/Counter.re
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
let count = ref(0);
/*
This is the set of action messages which are produced by this component.
* Add updates the components internal state.
*/
type action =
| Add

/*
This is the components internal state representation. This state object
is unique to each instance of the component.
*/
type state = {
count: int,
};

let counterReducer = (state, action) =>
switch(action) {
| Add => { count: state.count + 1 }
};

[@react.component]
let make = () => {
let (_state, dispatch) = React.useReducer(
(_, _) => Js.Obj.empty(),
Js.Obj.empty()
);

let countMsg = "Count: " ++ string_of_int(count^);
let (state, dispatch) = React.useReducer(counterReducer, { count: 0 });
let (globalState, globalDispatch) = GlobalCount.useGlobalCount();

let add = () => {
count := count^ + 1;
dispatch();
};
let countMsg = "Count: " ++ string_of_int(state.count);
let persistentCountMsg = "Persistent Count " ++ string_of_int(globalState);

<div>
<p> {ReasonReact.string(countMsg)} </p>
<button onClick={_ => add()}> {React.string("Add")} </button>
<button onClick={_ => dispatch(Add)}> {React.string("Add")} </button>
<p> {ReasonReact.string(persistentCountMsg)} </p>
<button onClick={_ => globalDispatch(GlobalCount.Increment)}>
{React.string("Add")}
</button>
</div>;
};

Expand Down
27 changes: 27 additions & 0 deletions examples/with-reasonml/components/GlobalCount.re
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
## Global Count
This captures the count globally so that it will be persisted across
the `Index` and `About` pages. This replicates the functionality
of the shared-modules example.
*/
type t = ref(int);

type action =
| Increment;

let current = ref(0);

let increment = () => {
current := current^ + 1;
current;
};

let reducer = (_state, action) => {
switch(action) {
| Increment =>
let updated = increment();
updated^
}
};

let useGlobalCount = () => React.useReducer(reducer, current^);