Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 16.4 Conditional Render Based on Promise

Tags:

reactjs

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>
  );
}
like image 642
GavinBelson Avatar asked Sep 04 '26 17:09

GavinBelson


1 Answers

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
  } 
}
like image 141
223seneca Avatar answered Sep 07 '26 09:09

223seneca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!