Last active
December 15, 2020 18:14
-
-
Save rogeriochaves/7a93eb8e49cf27e12aa9abdf025fbb79 to your computer and use it in GitHub Desktop.
Javascript Fetching State without Booleans
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
const NOT_ASKED = 'NOT_ASKED'; | |
const LOADING = 'LOADING'; | |
const SUCCESS = 'SUCCESS'; | |
const ERROR = 'ERROR'; | |
export const notAsked = () => ({ state: NOT_ASKED }); | |
export const loading = () => ({ state: LOADING }); | |
export const success = result => ({ state: SUCCESS, result }); | |
export const error = message => ({ state: ERROR, message }); | |
// example of use | |
let store = { | |
userProfile: notAsked(), | |
cartItems: notAsked() | |
}; | |
const loadUserProfile = () => { | |
store.userProfile = loading(); | |
fetch('/user/profile') | |
.then(res => res.json()) | |
.then(res => { | |
store.userProfile = success(res); | |
}) | |
.catch(e => { | |
store.userProfile = error(e.message); | |
}); | |
}; | |
const view = (store) => { | |
switch (store.userProfile.state) { | |
case NOT_ASKED: | |
return <button onClick={loadUserProfile}>Click here to load data</button>; | |
case LOADING: | |
return <div>Loading...</div>; | |
case SUCCESS: | |
return <h1>Welcome {store.userProfile.result.name}</h1>; | |
case ERROR: | |
return <h1>Oops there was a problem loading your data</h1>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment