0

I want to create a reusable function in Electron.js to handle Saving data irrespective of the model(e.g User, Employee, Product),so I passed Model as an argument, then call the specific Model during when the function is called. but I get this error

Error: Expected handler to be a function, but found type 'object'

This is my code

const User = require( '../database/models/Users.js');
ipcMain.handle('user:create', saveData(User));

async function saveData(_, data,Model) {
  try {
    const user = await Model.insert(data);
    return user;
  } catch (e) {
    console.log(e.message);
 }
}
eons
  • 388
  • 4
  • 21

1 Answers1

0

ipcMain.handle('user:create', saveData(User)); call function saveData(User) after app is started and it returns object. if you want to assign function to 'user:create' then without parameters it's ipcMain.handle('user:create', saveData); but with parameters it's.

ipcMain.handle('user:create', () => saveData(User));

is the same as

ipcMain.handle('user:create', function () {
   return saveData(User)
});
Lukas
  • 2,263
  • 1
  • 4
  • 15
  • Could you maybe expand your answer to explain why this solution will work? Thanks! – Alexander Leithner Oct 09 '22 at 07:24
  • @Lukas, i when i use your method i got this error, Error: An object could not be cloned. – eons Oct 10 '22 at 21:20
  • Because you probably just created one object and you're trying to create same without changing anything. – Lukas Oct 10 '22 at 21:36
  • Now it's problem with your function `saveData` – Lukas Oct 10 '22 at 21:37
  • @lukas, is there no work around it, creating saveData for each model sucks – eons Oct 10 '22 at 21:59
  • Check that https://stackoverflow.com/questions/63081902/unable-to-pass-objects-arrays-in-ipcrenderer-an-object-could-not-be-cloned-even – Lukas Oct 10 '22 at 22:04
  • @lukas, my problem is different, i am able to receive the user data when pass two argument to savaData(_,data) callback fucntion , but i have to create saveUser(_,data), saveProduct(_,data) ,saveEmployee(_,data) for each model. To avoid this that is while a want to add a third argument which is the model saveData(_,data,Model) then add the specific model during execution e.g ipcMain.handle('user:create',()=>saveData(specificModel)) . – eons Oct 10 '22 at 22:34