Last active
January 11, 2024 06:05
-
-
Save gpbl/b17d34783722e8120a1f to your computer and use it in GitHub Desktop.
Fluxible Store for keeping track of loading and error states for any payload (usage example in comments)
This file contains hidden or 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
import createStore from 'fluxible/utils/createStore'; | |
import hashObject from 'hash-object'; | |
import { omit } from 'lodash'; | |
const debug = require('debug')('App:StatusStore'); | |
const StatusStore = createStore({ | |
storeName: 'StatusStore', | |
handlers: { | |
LOAD_START: 'onLoadStart', | |
LOAD_SUCCESS: 'onLoadSuccess', | |
LOAD_FAILURE: 'onLoadFailure' | |
}, | |
_getHash(obj) { | |
const hash = hashObject(obj); | |
return hash; | |
}, | |
_setStatus(payload, isLoading, isLoaded, error) { | |
const status = { | |
isLoading: !!isLoading, | |
isLoaded: !isLoading && isLoaded && !error, | |
error: error | |
}; | |
const hash = this._getHash(payload); | |
this.status[hash] = status; | |
debug('Assigned status with hash %s', hash, status, payload); | |
}, | |
initialize() { | |
this.status = {}; | |
}, | |
onLoadStart(payload) { | |
this._setStatus(payload, true, false, null); | |
this.emitChange(); | |
}, | |
onLoadSuccess(payload) { | |
this._setStatus(payload, false, true, null); | |
this.emitChange(); | |
}, | |
onLoadFailure(payload) { | |
if (!payload.error) | |
console.warn('Missing error property in payload'); | |
this._setStatus(omit(payload, 'error'), false, false, payload.error); | |
this.emitChange(); | |
}, | |
get(payload) { | |
const hash = this._getHash(payload); | |
if (!this.status[hash]){ | |
debug('Cannot find status for hash %s, setting payload as not loaded', hash, payload); | |
this._setStatus(payload, false, true, null); | |
} | |
return this.status[hash]; | |
}, | |
dehydrate() { | |
return this.status; | |
}, | |
rehydrate(state) { | |
this.status = state; | |
} | |
}); | |
export default StatusStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of an action creator dispatching
LOAD_*
events:Example of a component getting the loading/error status from the StatusStore: