Search code examples
javascriptreactjsreact-proptypes

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() { /* ... */ }
}

Solution

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

      PropTypes.shape({
         then: PropTypes.func.isRequired,
         catch: PropTypes.func.isRequired
      })