Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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