Last active
July 30, 2019 22:24
-
-
Save sshh12/3cfa2cc404b5851b23360f1915547de6 to your computer and use it in GitHub Desktop.
Shridux - A superior global state management library.
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
// Shridux - A superior global state management library | |
class GlobalStore { | |
_initState = {}; | |
_bindings = {}; | |
setStore(newState) { | |
for(let key in newState) { | |
if(!(key in this._bindings)) { | |
this._bindings[key] = []; | |
} | |
for(let elem of this._bindings[key]) { | |
elem.setState({[key]: newState[key]}); | |
} | |
this._initState[key] = newState[key]; | |
} | |
} | |
bind(elem, keys) { | |
if(!elem.state) { | |
elem.setState({}); | |
} | |
for(let key of keys) { | |
if(!(key in this._bindings)) { | |
this._bindings[key] = []; | |
} | |
if(key in this._initState) { | |
elem.setState({[key]: this._initState[key]}); | |
} | |
this._bindings[key].push(elem); | |
} | |
} | |
} | |
export const store = new GlobalStore(); |
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 React, {Component} from 'react'; | |
import { http } from '../utils'; | |
import { store } from '../store'; | |
export default class App extends Component { | |
constructor(props) { | |
super(props); | |
this.runAsync(); | |
} | |
async runAsync() { | |
let user = await http.get('/api/user'); | |
if(!user.error) { | |
store.setStore({ | |
user: user, | |
loggedin: true, | |
ready: true | |
}); | |
} else { | |
store.setStore({ | |
ready: true | |
}); | |
} | |
} | |
render() { | |
return <Page /> | |
} | |
} |
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 React, {Component} from 'react'; | |
import { store } from '../store'; | |
export default class Page extends Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
componentDidMount() { | |
store.bind(this, ['loggedin', 'user', 'ready']); | |
} | |
render() { | |
if (!this.state.loggedin || !this.state.user.admin) { | |
if (this.state.ready) { | |
window.location = '/login'; | |
} | |
return <LoadingContent/> | |
} | |
return <Content/> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment