0

I have a fairly simple class component that needs access to some data from a service written in vanilla JS. It's simply an interface for the Web MIDI API, that must get access to the MIDI ports, then triggers a callback. I'm importing a function setMidiPorts to the MIDI service then calling it and sending the list of ports on MIDI success. I then need to render those ports in a drop down, but can't seem to get them updated in the component. I've tried passing them down as props from the parent, I've tried importing them directly. Nothing seems to work. I'm pretty new to react so I'm probably doing something pretty wrong, can anyone help me by pointing out where I'm going wrong.

window.inputs = [];

export const setMidiPorts = (inputs) => {
  window.inputs = inputs;
  console.log(inputs);
};

export default class Preferences extends Component {
  constructor(props) {
    super(props);
    this.state = {
      midiInputs: window.inputs,
      midiOutputs: [],
    };
  }
......

EDIT -

I'm looking at this question to see if I can update state from outside, but don't understand how it works properly.

Update component state from outside React (on server response)

jbflow
  • 384
  • 1
  • 11
  • 1
    There is a [`MIDIAccess.onstatechange`](https://developer.mozilla.org/en-US/docs/Web/API/MIDIAccess#event_handlers) event that you can listen for. – Aluan Haddad Jan 23 '21 at 14:35
  • Yes, you should make a custom hook with that and listen to them easily, search about custom hook if you didn't know about it. – b3hr4d Jan 23 '21 at 14:37
  • 1
    MIDIAccess.onstatechange isn't great for [compatibility](https://developer.mozilla.org/en-US/docs/Web/API/MIDIAccess#browser_compatibility). see this question for possible options: [Listening for variable changes in JavaScript](https://stackoverflow.com/a/37403125/13762301) – pilchard Jan 23 '21 at 14:42
  • @pilchard the whole API is experimental. It's always good to keep that in mind though. – Aluan Haddad Jan 23 '21 at 14:47
  • Thanks for the suggestions, how would I get the MIDIAccess into the react component though as it is currently outside and what is calling ```setMidiPorts``` – jbflow Jan 23 '21 at 14:48

1 Answers1

0

Thanks for everyones advice, I managed to solve it by following what it says here.

https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/

Adding this inside the component render

ref={(Preferences) => {window.Preferences = Preferences;}}

Then I was able to define the setMidiPorts function inside the component and call it from anywhere with window.Preferences.setMidiPorts

jbflow
  • 384
  • 1
  • 11