I am trying to conditionally render a block of code. The condition canProject can be either true or false. This is evaluated with the checkRole() function.
The problem is the checkRole() returns a promise. By the time the promise is returned the content is already rendered.
How can I use checkRole() to conditionally render a code block? Note, I use the canProject condition in a lot of places in the html code, so I would like to use it in the return ( as needed by adding {canProject &&
render() {
const canProject = checkRole('project'); //this returns a promise
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
);
}
Keep track of the promise's status in state:
this.state = {
promiseFulfilled: false
}
const canProject = checkRole('project').then(() => this.setState({promiseFulfilled: true}))
render() {
const { promiseFulfilled } = this.state
if (promiseFulfilled) {
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
)
} else {
return null
}
}
For posterity: this is the proper way to do so with more recent versions of React (version >16.8) using hooks:
const [ promiseFulfilled, setPromiseFulfilled ] = useState(false)
const canProject = checkRole('project').then(() => setPromiseFulfilled(true))
render() {
if (promiseFulfilled) {
return (
<div>
<div className="row">
{canProject &&
<div className="col-lg-4">
</div>
}
</div>
</div>
)
} else {
return null
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With