Where to download server data
I am using a reactive router and go to a component that gets an id in the url and have to use that id to get data from the server using an action.
At the moment I am calling the action creator in the hook componentWillMount
.
This works so far, but brings a problem. In the render method I have to check if myData
indeed exists with all its attributes before I can actually render.
@connect(state => {myData: state.etc.myData})
export default class extends React.Component {
componentWillMount = () => {
this.props.dispatch(
ActionCreators.getData(this.props.params.id)
)
}
render() {
if (this.props.myData.hasNotLoaded) return <br/>
...
}
}
Is there any other way to get data into storage before rendering without manual checks?
source to share
You can subscribe to onEnter
hook-and-send action router from that location.
const store = configureStore()
const routing = (<Router>
<IndexRoute onEnter={()=>store.dispatch(myLoadDataActionCreator())}/>
</Router>)
This way you can avoid setState
from the previous answer and not bind the component with the contraction.
source to share
You have to create a callback like:
_onChange() {
this.setState(myStore.getData());
}
Then, in the following reaction functions, do the following:
componentDidMount() {
myStore.addChangeListener(this._onChange);
},
componentWillUnmount() {
myStore.removeChangeListener(this._onChange);
}
I am assuming you are using mixins for a react router, if not look at the docs for it, they have some useful features worth looking at.
I don't think you will need this logic if
in the method render()
, react will handle this with virtual home control and know when to load it and data.
source to share