Skip to content

Instantly share code, notes, and snippets.

@justinbmeyer
Created September 29, 2021 22:05
Show Gist options
  • Save justinbmeyer/54ef153152760c4ba878d0e8fab8fa3e to your computer and use it in GitHub Desktop.
Save justinbmeyer/54ef153152760c4ba878d0e8fab8fa3e to your computer and use it in GitHub Desktop.
type ActionType =
| { type: "LOADING" }
| { type: "ADD_SUCCESS", payload: number }
| { type: "ADD_FAILURE", payload: any };
type StateType = {
count: number,
isActive: boolean,
error: any,
};
const initialState = {
count: 0,
isActive: false,
error: null,
};
function Counter() {
const [{count, isActive, error}, dispatch] = useReducer(
(state: StateType, action: ActionType) => {
switch (action.type) {
case "LOADING":
return {
...state,
isActive: true,
};
case "ADD_SUCCESS":
return {
...state,
count: state.count + action.payload,
isActive: false,
error: null,
};
case "ADD_FAILURE":
return {
...state,
isActive: false,
error: action.payload,
};
default:
return state;
}
},
initialState
);
const add = (amount: number) => {
dispatch({ type: "LOADING" });
// An api call to update the count state on the server
updateCounterOnServer(state.count + amount)
.then(() => {
dispatch({ type: "ADD_SUCCESS", payload: amount });
})
.catch((error) => {
dispatch({ type: "ADD_FAILURE", payload: error });
});
};
return (
<div>
<button onClick={() => add(2)}>Add</button>
<div>
<p>Steps: {count}</p>
<div>{isActive ? <Loader /> : "Processing completed"}</div>
{error && <p>Error: {error}</p>}
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment