Skip to content

Instantly share code, notes, and snippets.

@lanqy
Forked from jsiebern/StoreAndRouterExample.re
Created May 3, 2018 12:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lanqy/10a2c9f5d2ebfb445fc025ae1ac43c36 to your computer and use it in GitHub Desktop.
module Store = {
type actions =
| Increase
| Decrease;
type state = {count: int};
type store = {
state,
dispatch: actions => unit
};
let component = ReasonReact.reducerComponent("Store");
let make = (~render, _children) => {
...component,
initialState: () => {count: 0},
reducer: (action, state) =>
switch action {
| Increase => ReasonReact.Update({count: state.count + 1})
| Decrease => ReasonReact.Update({count: state.count - 1})
},
render: self =>
render({state: self.state, dispatch: action => self.send(action)})
};
};
module Login = {
let component = ReasonReact.statelessComponent("Login");
let make = _children => {
...component,
render: _self =>
<div>
<button onClick=(_event => ReasonReact.Router.push("/loggedin"))>
(ReasonReact.stringToElement("Login"))
</button>
</div>
};
};
module Screen = {
let component = ReasonReact.statelessComponent("Screen");
let make = (~store: Store.store, _children) => {
...component,
render: _self =>
<div>
<span>
(
ReasonReact.stringToElement(
"Count: " ++ string_of_int(store.state.count)
)
)
</span>
<br />
<button onClick=(_event => store.dispatch(Increase))>
(ReasonReact.stringToElement("Increase"))
</button>
<button onClick=(_event => store.dispatch(Decrease))>
(ReasonReact.stringToElement("Decrease"))
</button>
</div>
};
};
module Router = {
type route =
| Login
| Screen;
type action =
| SwitchRoute(route);
type routerState = {activeRoute: route};
let component = ReasonReact.reducerComponent("Router");
let make = _children => {
...component,
initialState: () => {activeRoute: Login},
reducer: (action, _state) =>
switch action {
| SwitchRoute(r) => ReasonReact.Update({activeRoute: r})
},
subscriptions: self => [
Sub(
() =>
ReasonReact.Router.watchUrl(url => {
switch url.path {
| ["loggedin"] => self.send(SwitchRoute(Screen))
| _ =>
Js.log("Could not find route");
Js.log(url);
};
();
}),
ReasonReact.Router.unwatchUrl
)
],
render: self =>
<Store
render=(
store =>
<div>
(
switch self.state.activeRoute {
| Screen => <Screen store />
| Login => <Login />
}
)
</div>
)
/>
};
};
let component = ReasonReact.statelessComponent("Counter");
let make = _children => {...component, render: _self => <Router />};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment