Created
September 29, 2021 22:05
-
-
Save justinbmeyer/54ef153152760c4ba878d0e8fab8fa3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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