Hi,
I am trying to run a simple script to test the IPC in Electron. I want to get data from an open api. The call starts from the renderer through preload (invoke), the main receives the call and fetch the data. The main could get the message of fetch, but how to return the data back to the renderder?. I use return in the main but get 'undefined' value in renderer. Any suggestion? Thanks
#Fetch api
18 messages · Page 1 of 1 (latest)
incorrect return usage
Use the ipcMain and ipcRenderer modules to communicate between Electron processes
what do you return? use console.log() in the ipcMain.handle to check if you are not returning "undefined"
fetch response.body and stuff may not be directly accessable without calling appropriate methods for it first
I tried to return a simple string, but it is also undefined, when I console log it in the renderer
const response = fetch(url);
const body = response.text();
return body;
show the code
ok
main.ts
ipcMain.handle('fetch', async (event, url:string) =>{
const data = await axios.get(url)
.then((response) => {
return response
// };
})
.catch((error) => {
console.log('handle error: ' + error);
})
return data
})
}
preload.ts
const api = {
fetch: async (url,options):Promise<T> => {
await ipcRenderer.invoke('fetch', url)
}
contextBridge.exposeInMainWorld('api', api)
renderer
async call(){
const data = await window.api.fetch(https://reddit.com/r/aww.json?raw_json=1)
console.log(data)
}
timosh was right, you are using the return wrong in this code part.
the whole code is a bit confusing. you are using .then() AND await. As far as i know, that cannot work. remove .then() part. use await only. the return in the then() part cannot work anyway because it would try to return after ipcMain.handle() is already complete (that is called fire and forget)
ipcMain.handle('fetch', async (event, url:string) =>{
const data = await axios.get(url)
.then((response) => {
return response
// };
})
.catch((error) => {
console.log('handle error: ' + error);
})
return data
})
}
i have no idea of axios, but try that:
ipcMain.handle('fetch', async (event, url:string) =>{
const data = await axios.get(url);
return data;
})
}
Thanks. I do not think this will work. I understand we need then when we deal with promises!
a newer approach is to use async await with promises instead of do().then().catch() you would use { await do() } catch() { .... }. Makes code more readable, too
in the case of this .handle() you have no other choice anyway