Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use PropTypes to express that a prop is a Promise?

PropTypes are helpful for debugging because they show a warning when an expectations is not met. Beyond that, they're also nice to express the intention of how a component is meant to be used.

If I have a component that accepts a prop with a value that can be a promise, is there some way I can express that using PropTypes? I'm picturing either something direct like PropTypes.promise, or some way to express the concept of a "thenable" using building-block PropTypes.

Here is a highly simplified example to show my intended use case:

class SomeComponent extends Component {
  static propTypes = {
    someDataPromise: PropTypes.object // <-- can I be more expressive here?
  }

  state = {
    isLoading: false
  }

  async handleSubmit() {
    this.setState({ isLoading: true });

    const data = await this.props.someDataPromise;
    const response = await fetch(`/some/api/endpoint?data=${data}`);
    // do something with the response

    this.setState({ isLoading: false });
  }

  render() { /* ... */ }
}
like image 895
Michael Kropat Avatar asked Oct 15 '19 18:10

Michael Kropat


2 Answers

You could use an object with a particular shape e.g.

  PropTypes.shape({
     then: PropTypes.func.isRequired,
     catch: PropTypes.func.isRequired
  })
like image 123
nicholascm Avatar answered Sep 21 '22 18:09

nicholascm


Another way you can express that a prop is a Promise is to use PropTypes.instanceOf(). Important caveat: this only works if your promises are instances of the Promise class:

static propTypes = {
  someDataPromise: PropTypes.instanceOf(Promise)
}
like image 45
Daniel Bank Avatar answered Sep 23 '22 18:09

Daniel Bank