Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active July 16, 2019 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidev275/5b7cbc85c27501c6730785a0073566f1 to your computer and use it in GitHub Desktop.
Save reidev275/5b7cbc85c27501c6730785a0073566f1 to your computer and use it in GitHub Desktop.
import React from "react";
const delay = () => new Promise((res, rej) => setTimeout(res, 2000));
type Model = { count: number };
type Message = "increment" | "decrement" | "sendDelay";
const Counter: React.FC<Model> = (initial: Model) => {
const [model, emit] = React.useReducer((m: Model, msg: Message): Model => {
switch (msg) {
case "increment":
return { count: m.count + 1 };
case "decrement":
return { count: m.count - 1 };
case "sendDelay":
delay().then(() => emit("increment"));
return m;
}
}, initial);
return (
<div className="App">
<button onClick={() => emit("decrement")}>-</button>
{model.count}
<button onClick={() => emit("increment")}>+</button>
<button onClick={() => emit("sendDelay")}>Increment async</button>
</div>
);
};
const App: React.FC = () => {
return <Counter count={9} />;
};
export default App;
import React from "react";
type Model = { count: number };
type Message = "increment" | "decrement";
const Counter: React.FC<Model> = (initial: Model) => {
const [model, emit] = React.useReducer((m: Model, msg: Message): Model => {
switch (msg) {
case "increment":
return { count: m.count + 1 };
case "decrement":
return { count: m.count - 1 };
}
}, initial);
return (
<div className="App">
<button onClick={() => emit("decrement")}>-</button>
{model.count}
<button onClick={() => emit("increment")}>+</button>
</div>
);
};
const App: React.FC = () => {
return <Counter count={9} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment