1

Am working with electron and encountering and issue that I cannot for the life of me fix despite it being so simple, where my received data is showing as undefined in renderer, yet shows correctly when console.log(the data) in main.

All I am trying to do is have main read a .JSON file and send the contents of it to the renderer to be stored and used.

Here is renderer code:

let table_data

ipcRenderer.send('request_data');

ipcRenderer.on('activity_data', (event, activityData) => {
  console.log('Data received');
  console.log(activityData);
//This returns undefined
});

ipcRenderer.on('activity_data_error', (event, error) => {
  console.error('Error fetching activity data:', error);
});

Here is main code:


// Respond to ipc Renderer request activity_data
ipcMain.on('request_data', (event, data) => {
    try {
      const rawData = fs.readFileSync('renderer/js/activity_data.json', 'utf8');
      const activityData = JSON.parse(rawData);
      console.log('activity_data', activityData);
      //This returns correct JSON data
      event.reply('activity_data', activityData);
    } catch (error) {
      console.error('Error reading or parsing JSON file:', error);
      event.reply('activity_data_error', error);
    }
  });
benmag11
  • 25
  • 3
  • 1
    Any reason for not using `.handle` instead? https://www.electronjs.org/docs/latest/api/ipc-main#ipcmainhandlechannel-listener The code looks fine though, as long as the log is good it should work. – briosheje May 24 '23 at 20:14
  • Could you elaborate on what as long as the log is good means. And as to why i didn't use .handle was simply because it looked more confusing in the documentation so found this easier to understand might give try now though. Thank you for your answer. – benmag11 May 24 '23 at 21:19
  • Try `event.sender.send('activity_data', activityData)` in main. – Timur May 25 '23 at 05:30
  • @benmag11 What I mean is that as long as in your ipc main the log is correct you should get the message back. Using `.handle` simplifies think because instead of subscribing to a channel you can simply call the handle and await it (because it returns a Promise), so you don't need to deal for additional paremeters and additional boilerplate you're not interested in. Worst case scenario to me is that `activityData` for some reasons is not a regular Object, although it should be. Best way to check this is to JSON.stringify it before sending in `event.reply`, although that should not be the ase. – briosheje May 25 '23 at 07:19

1 Answers1

0

the way you use ipc looks very outdated. use ipcRenderer.invoke() in renderer and ipcMain.handle() in main.

https://www.electronjs.org/docs/latest/tutorial/ipc

May help too if handle()/on() is not called at all: in main put the ipcMain.on() and ipcMain.handle() before the browserWindow.loadURL().

Welcor
  • 2,431
  • 21
  • 32