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;
});
});
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);
});