FE Dev - PandaCare
A state is a representation of a system in a given time. State refers to the data stored in Application in the form of a string, arrays, object, etc.
ex. is user logged-in?, is Loading?, is Error?
Basically, we as a frontend dev is getting paid to manage states
isLoading?
isError?
isAbela?
basic fetch and set data
loading too long, add loading indicator
sometime we don't get what we want, display error
sometime we have moody user, who suddenly want to cancel the request
What is?
by David K Piano
by rewriting our owsem app with state machine
function dogReducer(state, event) {
switch (event.type) {
case "FETCH":
return {
...state,
status: "loading"
};
case "RESOLVE":
return {
...state,
status: "success",
dog: event.data
};
case "REJECT":
return {
...state,
status: "failure",
error: event.error
};
case "CANCEL":
return {
...state,
status: "idle"
};
default:
return state;
}
}
const initialState = {
status: "idle",
dog: null,
error: null
};
you can use reducer
function DogFetcher() {
// 'idle' or 'loading' or 'success' or 'error'
const [status, setStatus] = useState('idle');
}
you can use as simple as useState
function DogFetcher() {
// 'idle' or 'loading' or 'success' or 'error'
const [status, setStatus] = useState('idle');
const isLoading = status === 'loading';
return (
// ...
<button disabled={isLoading}>
{/* ... */}
</button>
// ...
);
}