Skip to content

Instantly share code, notes, and snippets.

@rogeriochaves
Last active December 15, 2020 18:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogeriochaves/7a93eb8e49cf27e12aa9abdf025fbb79 to your computer and use it in GitHub Desktop.
Save rogeriochaves/7a93eb8e49cf27e12aa9abdf025fbb79 to your computer and use it in GitHub Desktop.
Javascript Fetching State without Booleans
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