Reputation: 35
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);
}
});
Upvotes: 2
Views: 1566
Reputation: 3083
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().
Upvotes: 2