Answer the question
In order to leave comments, you need to log in
How to initialize user data in React?
Where and how best to perform the initial initialization of the application, having a user token on the client.
When opening the page, I want to check the validity of the token, and then launch it at the requested URI.
Now the App component looks like this:
import store from '../store'
class Application extends React.PureComponent {
constructor (props) {
super(props)
this.state = {
initialized: false
}
}
componentDidMount () {
// verifyToken - action, в котором происходит запрос к серверу
store.dispatch(verifyToken()).then(() => {
this.setState({ initialized: true })
})
}
renderPreloader () {
return <div className='app-preloader'><Spinner /></div>
}
renderApp () {
return <BrowserRouter>
<Provider store={store}>
<Switch>
// SecurityRoute - компонент, проверяющий в store наличие у пользователя прав на просмотр страницы. Если такого права нет - редиректит
<SecurityRoute field='username' deny path='/login' component={PageAuth} />
<Route component={PageMain} />
</Switch>
</Provider>
</BrowserRouter>
}
render () {
return this.state.initialized ? this.renderApp() : this.renderPreloader()
}
}
Answer the question
In order to leave comments, you need to log in
store.dispatch(init()); // тут
const root = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDom.render(root, document.getElementById('root'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question