#Fetch api

18 messages · Page 1 of 1 (latest)

brave gazelle
#

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

frozen canyon
#

incorrect return usage

brave gazelle
#

Ok, thanks

#

In the example, there is also a return

fallow raft
#

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

brave gazelle
#

I tried to return a simple string, but it is also undefined, when I console log it in the renderer

fallow raft
#
const response = fetch(url);
const body = response.text();
return body;
#

show the code

brave gazelle
#

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

fallow raft
#

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;
  })
}
brave gazelle
#

Thanks. I do not think this will work. I understand we need then when we deal with promises!

fallow raft
#

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

brave gazelle
#

ok. got it. I forgot js. Thank you. I will try your suggestion

#

it is not working. I removed all async -await. just tried to send a string from the main back to the renderer