Last active
February 21, 2017 22:15
-
-
Save viankakrisna/717d5b5c3a392cf153af378d76cbe6b5 to your computer and use it in GitHub Desktop.
state-component -- state manager using React's own state
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
let persist = false; | |
let ref = null; | |
export function setStateContainer(componentInstance, isPersist) { | |
ref = componentInstance; | |
persist = isPersist; | |
} | |
export function isPersist() { | |
return persist; | |
} | |
export default function getStateContainer() { | |
return ref; | |
} | |
export function getState(key, defaults) { | |
if (key) { | |
return getStateContainer().state[key] || defaults; | |
} | |
return getStateContainer().state; | |
} | |
export function setState(state, cb) { | |
getStateContainer().setState(state, newState => { | |
if (typeof cb === "function") { | |
cb(newState); | |
} | |
}); | |
} | |
export function loadState() { | |
if (isPersist() && localStorage) { | |
return JSON.parse(localStorage.getItem("state")); | |
} | |
} | |
export function saveState(state) { | |
if (isPersist() && localStorage) { | |
return localStorage.setItem("state", JSON.stringify(state)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment