Created
February 3, 2016 19:46
-
-
Save sebastiandeutsch/e6148ca0741cc355248c to your computer and use it in GitHub Desktop.
Checking the routes of ReactRouter for loaders and the executing them.
This file contains 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 from 'react' | |
import RouterContext from 'react-router/lib/RouterContext' | |
class StoreLoader extends React.Component { | |
static childContextTypes = { | |
storeIsSynchronized: React.PropTypes.bool | |
}; | |
constructor(props) { | |
super(props); | |
let storeIsSynchronized = true; | |
this.props.routes.forEach((route) => { | |
if(route.loader) { | |
let loader = new route.loader(); | |
if(loader.needsToSyncStore(this.props.params, this.props.store)) { | |
storeIsSynchronized = false; | |
} | |
} | |
}); | |
this.state = { | |
storeIsSynchronized: storeIsSynchronized | |
}; | |
} | |
getChildContext() { | |
return { | |
storeIsSynchronized: this.state.storeIsSynchronized | |
} | |
} | |
syncStore() { | |
this.props.routes.forEach((route) => { | |
if(route.loader) { | |
let loader = new route.loader(); | |
if(loader.needsToSyncStore(this.props.params, this.props.store)) { | |
loader.syncStore(this.props.params, this.props.store).then( | |
(response) => { | |
this.setState({ storeIsSynchronized: true }); | |
}, | |
(error) => { | |
console.log(error); | |
} | |
); | |
} | |
} | |
}); | |
} | |
componentDidMount() { | |
this.syncStore(); | |
} | |
componentWillReceiveProps(nextProps) { | |
this.syncStore(); | |
} | |
render() { | |
return <RouterContext {...this.props} />; | |
} | |
} | |
export default StoreLoader; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment