Skip to content

Instantly share code, notes, and snippets.

@eric-wood
Last active February 8, 2017 22:11
Show Gist options
  • Save eric-wood/39352ce1abc85cff3400389cc71c47be to your computer and use it in GitHub Desktop.
Save eric-wood/39352ce1abc85cff3400389cc71c47be to your computer and use it in GitHub Desktop.
function withMidi(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
hasMidi = Boolean(navigator.requestMIDIAccess);
this.state = {
access: undefined,
input: undefined,
output: undefined,
status: hasMidi ? 'pending' : 'unavailable'
};
this.refreshIO = this.refreshIO.bind(this);
this.requestSuccess = this.requestSuccess.bind(this);
this.requestFailure = this.requestFailure.bind(this);
if(hasMidi) {
navigator.requestMIDIAccess({ sysex: props.sysex })
.then(this.requestSuccess, this.requestFailure);
}
}
requestSuccess(access) {
access.addEventListener('onstatechange', this.refreshIO);
this.setState({ access });
this.refreshIO();
}
refreshIO() {
this.setState({
input: MIDI.getInput(this.state.access),
output: MIDI.getOutput(this.state.access)
});
}
requestFailure(error) {
this.setState({
status: 'declined'
});
}
render() {
return <WrappedComponent midi={this.state} {...this.props} />;
}
}
}
@1000hz
Copy link

1000hz commented Feb 8, 2017

If you're using Babel stage-2+ presets, you can auto-bind the functions by declaring them as arrow-function class properties

requestSuccess = (access) => {
  ...
}

You need to pass access to this.refreshIO()

also hasMidi is being declared as a global. Otherwise, LGTM!

@1000hz
Copy link

1000hz commented Feb 8, 2017

P.S. this.setState() updates state asynchronously, so accessing this.state.access in refreshIO might not pull the right value. You can force refreshIO's setState call to be atomic by passing a function instead of an object.

    refreshIO() {
      this.setState((prevState, props) => ({
        input: MIDI.getInput(prevState.access),
        output: MIDI.getOutput(prevState.access)
      }));
    }

See https://facebook.github.io/react/docs/react-component.html#setstate for more info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment