GavinBelson
GavinBelson

Reputation: 2784

React 16.4 Conditional Render Based on Promise

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>
  );
}

Upvotes: 3

Views: 995

Answers (2)

GavinBelson
GavinBelson

Reputation: 2784

I think this is the most elegant way to achieve this:

constructor() {
  super();
  this.state = {canProjectR: false}; //set to false initally
}

//set the canProjectR to the response which is true or false
componentDidMount() {
  this.checkRole('project').then(res => { this.setState({ canProjectR: res}) });
}

//use this.state.canProject && as needed
render() {
  return (
    <div>
      <div className="row">
        {this.state.canProject && 
          <div className="col-lg-4">
          </div>
        }
      </div>
    </div>
  );
}

Upvotes: 0

223seneca
223seneca

Reputation: 1176

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
  } 
}

Upvotes: 4

Related Questions