Last active
October 20, 2017 00:39
-
-
Save dmachat/117b9e9ca49957dfc285e75c7e2845a5 to your computer and use it in GitHub Desktop.
a simple store
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
class ParentComponent extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
data; // data lives here | |
}; | |
this.setStore = this.setStore.bind(this); | |
} | |
// this gets called when the promise resolves in DataComponentOne | |
setStore(data) { | |
this.setState({ data }); | |
} | |
render() { | |
const { setStore } = this; | |
// when this.state.data gets set it triggers an update on both children | |
// links to swap between them won't unmount this parent state | |
const { data } = this.state; | |
return ( | |
<View> | |
<Route path='/getData' render={props => <DataRouteOne {...props} {...{ setStore, data }} />} /> | |
<Route path='/showData' render={props => <DataRouteTwo {...props} {...{ data }} />} /> | |
</View> | |
); | |
} | |
} | |
class DataRouteOne extends Component { | |
componentDidMount() { | |
const { setStore } = this.props; | |
// careful with the binding here, since the function is being called elsewhere | |
fetch('/url').then(data => setStore(data)); | |
} | |
render() { | |
// we don't keep state in this component. it flows back from the parent | |
const { data } = this.props; | |
return <View>{data}</View>; | |
} | |
} | |
// this is an easy stateless functional component that will just render whatever is in data prop | |
function DataRouteTwo({ data }) { | |
return <View>{data}</View> | |
} | |
function App() { | |
// data providers live at the root | |
return ( | |
<Router> | |
<ParentComponent /> | |
</Router> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment