ipcRenderer in React component constructor

5.6k Views Asked by At

I have an app using Electron, React, and React Router. I'm using ipcRenderer in the component constructor to send events from my component to the main Electron process. After I added React Router to the mix, I noticed that my ipcRenderer event was getting added again and again each time I left and came back to the component. I figure it's because React Router is mounting and unmounting the component as needed.

I found a way around the issue by checking if the event already has been registered like this:

if (!ipcRenderer._events['open-file-reply']) {
  ipcRenderer.on('open-file-reply', (event, fileContents) => {
    if(fileContents){
      this.setState({
        data: JSON.parse(fileContents)
      }); 
    }   
  }); 
} 

I'm just wondering if there is a more correct way to do this. Does ipcRenderer.on belong in the constructor anyway, or is there a more appropriate place to put it?

EDIT

This is the best solution I've come up with so far:

import {ipcRenderer} from  'electron';

/* inside React component */
constructor(props) {
  super(props);
  // ...
  this.loadFileListener = this.loadFileListener.bind(this);
  ipcRenderer.on('open-file-reply', this.loadFileListener);
}

componentWillUnmount() {
  ipcRenderer.removeAllListeners(['open-file-reply']);
}

loadFileListener(event, fileContents) {
  // set state and stuff...
}
1

There are 1 best solutions below

0
On

I don't think you should be setting up IPC until the component is mounted, so I would suggest this approach:

 constructor(props) {
   super(props)
   this._loadFileListener = this._loadFileListener.bind(this)
 }

 componentDidMount() {
   ipcRenderer.on('open-file-reply', this._loadFileListener)
 }

 componentWillUnmount() {
   ipcRenderer.removeListener('open-file-reply', this._loadFileListener)
 }