Reputation: 553
I have a function in utils that do this:
export function getUserRole() {
return (
localStorage.getItem('token') &&
jwtDecode(localStorage.getItem('token')).role
)
}
I call it in a component like so
class App extends Component {
constructor(props) {
this.role = getUserRole()
}
render() {
console.log(this.role) //admin, member
return (
<Provider store={this.role === 'member' ? store : adminStore}>
<BrowserRouter>
<div className="App">
<Switch>
<Route path="/login" component={Login} />
</Switch>
</div>
</BrowserRouter>
</Provider>
)
}
}
how do I switch store here? Above code worked but will load the adminStore first then load store if the role is member. How can I prevent loading both store and adminStore into my app?
Upvotes: 1
Views: 54
Reputation: 104369
Its because componentDidMount
will get called after the initial rendering, and during the first rendering this.role
will be undefined.
class App extends Component {
componentDidMount() {
this.role = getUserRole()
console.log(this.role); // you will see the correct value
}
render() {
console.log(this.role) //undefined
return (
<div>Hello</div>
)
}
}
Why its working with componentWillMount method?
Because that method get called before the initial rendering means before the render method triggered first time.
Solution:
You can call that method in the constructor, like this:
class App extends Component {
constructor() {
super()
this.role = getUserRole()
}
.....
}
As per Doc:
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree).
componentWillMount is invoked just before mounting occurs. It is called before render().
Upvotes: 1
Reputation: 2314
Well, the first render occurs before the component mounts and componentDidMount is called, so the first render will indeed have undefined.
What you should do is add some logic to say:
render() {
if (this.role === null) {
// Render loading state ...
} else {
// Render real UI ...
}
}
Check here for more info.
Upvotes: 0