ipcMain help needed

497 Views Asked by At

I am trying to send a reply message back to my render. In the render I get a print out of "undefined" in the console log. I am trying to get the json response back from my api call

So far I tried the follow

ipcMain.on("get_scenes", (event, arg) => {
  axios.get("http://localhost:60704/getMovies").then(function (response) {
    // handle success
    console.log("my message", response);
  });
  event.returnValue = response;
});

and

ipcMain.on("get_scenes", (event, arg) => {
  axios.get("http://localhost:60704/getMovies").then(function (response) {
    // handle success
    console.log("my message", response);
    event.returnValue = response;
  });
  
});
2

There are 2 best solutions below

0
On BEST ANSWER

The problem in example #1 is that the response variable can't be gotten from outside the function it's declared in.

The problem in example #2 is that axios.get( is asynchronous which means it doesn't get the response instantly like a synchronous function would. This means that event.returnValue would be set too late and the response wouldn't work.

The solution is to reply with a new message like this:

ipcMain.on("get_scenes", (event, arg) => {
    axios.get("http://localhost:60704/getMovies").then(function (response) {
        event.sender.send('scenes_response', response);
    });
});

Then recieve it in the renderer like this:

var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('scenes_response', function (evt, messageObj) {
    // messageObj Now contains the response.
    console.log(messageObj);
});
0
On

try win.webContetens.send instead of event.sender.send

like this,

ipcMain.on("get_scenes", (event, arg) => {
    axios.get("http://localhost:60704/getMovies").then(function (response) {
        win.webContents.send('scenes_response', response);
    });
});