JSFiddle - React, Tailwind, and code Playground
by mtclose
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
h1 {
font-size: 1.5rem;
}
h2 {
font-size: 1.2rem;
}
React
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
const AsyncCounterReducer = () => {
const [state, dispatch] = React.useReducer(reducer, { count: 0 });
const incrementCountAsync = () => {
return new Promise((resolve) => setTimeout(resolve, 1000))
.then(() => dispatch({ type: 'increment' }));
};
return (
<div>
<h1>Async Counter</h1>
<h2>Count: {state.count}</h2>
<button onClick={incrementCountAsync}>Increment</button>
</div>
);
}
ReactDOM.render(<AsyncCounterReducer />, document.querySelector("#app"))