Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Last active November 11, 2018 15:22
Show Gist options
  • Save busypeoples/42a5290bc1a489a4f7025bc556d8ebb7 to your computer and use it in GitHub Desktop.
Save busypeoples/42a5290bc1a489a4f7025bc556d8ebb7 to your computer and use it in GitHub Desktop.
Understanding Reducer in ReasonML
let se = ReasonReact.stringToElement;
type state = int;
type actions =
| Inc
| IncWithSideEffect
| SideEffect
| DoNothing
| SilentIncUpdate
| SilentIncUpdateWithSideEffect;
let component = ReasonReact.reducerComponent("Main");
let make = (_children) => {
...component,
initialState: () => 0,
reducer: (action, state) =>
switch action {
| Inc => ReasonReact.Update(state + 1)
| IncWithSideEffect =>
ReasonReact.UpdateWithSideEffects(
state + 1,
((self) => Js.log("Updated State: " ++ string_of_int(self.state)))
)
| SideEffect =>
ReasonReact.SideEffects(
(
(self) =>
Js.log(
"Side effect only logging State: " ++ string_of_int(self.state)
)
)
)
| DoNothing => ReasonReact.NoUpdate
| SilentIncUpdate =>
/* Does not trigger a re-rendering! */ ReasonReact.SilentUpdate(0)
| SilentIncUpdateWithSideEffect =>
/* Does not trigger a re-rendering! */
ReasonReact.SilentUpdateWithSideEffects(
0,
(
(self) =>
Js.log(
"Silent Update With SideEffects Log: "
++ string_of_int(self.state)
)
)
)
},
render: ({state, reduce}) =>
<div>
<div> (se(string_of_int(state))) </div>
<button onClick=(reduce((_event) => Inc))> (se("Update Inc")) </button>
<button onClick=(reduce((_event) => IncWithSideEffect))>
(se("Update Inc With Side Effect!"))
</button>
<button onClick=(reduce((_event) => SideEffect))>
(se("No Update just Side Effect!"))
</button>
<button onClick=(reduce((_event) => DoNothing))>
(se("Do Nothing"))
</button>
<button onClick=(reduce((_event) => SilentIncUpdate))>
(se("Silent Inc Update!"))
</button>
<button onClick=(reduce((_event) => SilentIncUpdateWithSideEffect))>
(se("Silent Inc Update With Side Effect!"))
</button>
</div>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment