A
A
Artem2019-05-05 18:34:52
RESTful API
Artem, 2019-05-05 18:34:52

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

1 answer(s)
A
Anton Spirin, 2019-05-05
@Cruper

store.dispatch(init());  // тут

const root = (
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>
);

ReactDom.render(root, document.getElementById('root'));

This way, the validation and getting user data requests will be initiated before the application is mounted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question