Reputation: 39
I have a ReactJS web app that it has to initiate some data at the starting load time (after entering Url in the browser). For example, my web app calls API for checking whether the token is valid, loading profile information ... I want to show loading page at that time until the initial process finishes.
How to do that?
I use react router v4 in my project.
The initial process happens only one time until the user closes tab of my app in the browser.
My web app have multiple routes. It means that my app have many pages. The initial must always run after user enter whatever route in browser Url. For example my app have routes like that:
<route path="/about" component={about}>
<route path="/admin" component={admin}>
<route path="/dashboard" component={dashboard}>
When the user enters http://localhost:3000/about or http://localhost:3000/admin or localhost:3000/dashboard in the browser, then my App must init data and shows loading page, when init finish my app render the corresponding page.
Update To clear question:
The solution of my question can be:
But this solution have problem that where put the code doing data initiate? you know that user can enter whatever page url to access my web app so that i have to add the code doing init to every pages of my web app. This not good way because code repeats.
So i want to have one component that doing data initial and render loading until it finish. After initiate finishes, it render corresponding page depends on url. How to implement that using React router v4?
Upvotes: 0
Views: 3040
Reputation: 8522
You can use conditional rendering.
Initiate data loading in componentWillMount
or componentDidMount
and setState
when data loading is completed. Then apply conditional rendering in the render method based on the status of the state.
You can take help from this snippet:
constructor(props){
this.state = {status: null}
}
componentWillMount(){
function_initiateDataLoading((data)=>{
this.setState({status: data})
})
}
render(){
return this.tate.status == null ? <LoadingComponent/> : <FinalComponent/>
}
Upvotes: 1