ipcRenderer and variable scope


#1

Hi, I’m new to Electron. I’m using ipcRenderer to receive data from the main process. however I don’t understand the following issue. The args value is received correctly but it looks like the item variable is never updated. As I need to use the args value outside of the callback how can I solve this?

const {ipcRenderer} = require ('electron');
var item = 0;

ipcRenderer.on('sender', (event, arg) => {
	item = arg; //this doesn't work
	console.log("my arg: " + arg); //this works as expected
});

console.log(item); //always prints 0

Thank you!


#2

Hi,

If the Code you’ve posted is 1:1 equivalent:

Keep in Mind how the execution chain is.

  • Renderer JS will be loaded
  • Event Handler will be defined (not executed)
  • Value “item” will be logged

    time passes
  • Your main will fire the sender event which will change value of item

#3

Hi, thanks for the reply.
Is here any other way that I can pass a value from main to renderer without having to deal with callbacks? I have a whole program with threejs and leap motion controller to run and running it inside the callback because of that single value doesn’t sound very good, so another solution would be perfect.

Thank you"


#4

Hi,

I have the same Problem. I use Ionic in Electron. So I also can’t set global variable as here for instance item in the ipcRender.on eventlistener.

So anybody here who can solve that issue of franz1900? Or Franz1900, do you have a solution now? Also helping hints are welcome. a code example would be genius.

Looking for reply soon.