Problem where ipcMain.handle() fails to send a value back to ipcRenderer.invoke()

After spending 2 days struggling with this problem, scouring the API documentation of Electron.js and various websites, I am turning to you all as my final hope:

Here are the 3 files that are causing the issue:

main.ts (excerpt):

app.whenReady().then(() => {
  ipcMain.on("set-credentials", (event, args: object) => {
    encryptedCredentials = safeStorage.encryptString(JSON.stringify(args));
  });

  ipcMain.handle("get-credentials", async (event, args: null) => {
    const decryptedCredentials = await JSON.parse(
      safeStorage.decryptString(encryptedCredentials)
    );
    return decryptedCredentials;
  });

  createWindow();
});

preload.ts (full code):

import { ipcRenderer, contextBridge } from "electron";

contextBridge.exposeInMainWorld("electronAPI", {
  setStoredCredentials: async (args: object) =>
    await ipcRenderer.send("set-credentials", args),
  getStoredCredentials: () => {
    ipcRenderer.invoke("get-credentials");
  },
});

Login.tsx (excerpt):

const setStoredCredentials = async (e: any, service: string) => {
    e.preventDefault();
    window.electronAPI.setStoredCredentials({
      service,
      username: e.target[0].value,
      password: e.target[1].value,
    });
    setTimeout(() => {
      window.electronAPI.getStoredCredentials().then(
        (data: object) => { console.log(data); } //testing 

      )
    }, 1000)
  };

(the electron app features React)

Despite trying methods like ipcMain.on and ipcRenderer.sendSync with event.returnValue, I still encountered an error that says:

caught TypeError: Cannot read properties of undefined (reading 'then')
 

The other methods I attempted resulted in either the same error or an undefined value.

Answer №1

For efficient two-way IPC, utilizing async/await within the renderer process is essential. The IPC process may experience delays without async/await, resulting in the original call returning a Promise.

It is recommended to incorporate await in both setStoredCredentials and getStoredCredentials functions.

const setStoredCredentials = async (e: any, service: string) => {
    e.preventDefault();
    await window.electronAPI.setStoredCredentials({
      service,
      username: e.target[0].value,
      password: e.target[1].value,
    });
    setTimeout(() => {
      await window.electronAPI.getStoredCredentials().then(
        (data: object) => { console.log(data); } //testing 

      )
    }, 1000)
  };

If the code shown above functions correctly, the setTimeout can be eliminated.

Answer №2

Just wanted to clear something up:

Before returning the value in main.ts, if I use console.log() to display it, everything works perfectly.

I've declared the cryptedCredentials variable like this: let cryptedCredentials: Buffer;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function to increase the number of days on a date in Angular is experiencing technical issues

I'm facing an issue where I need to add 12 days to a specific date, but the new date is not coming out as expected. Below is the code snippet: addDays(days: number): any { let startDate = new Date(this.selectedDeliveryDate); let endDate = new ...

Getting the checkbox count value in a treeview upon successful completion of an AJAX request

After successful JSON Ajax response, a treeview structure with checkboxes is displayed. I need to capture the number of checkboxes checked when the save button is clicked. @model MedeilMVC_CLOUD.Models.UserView <script type="text/javascript"> ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

When using the require() function in Node.js, the period "." is not being recognized as part of the command and

I recently encountered a problem while working on my project and reorganizing my files. I noticed that the "." in my requires are not being parsed correctly. Upon running my program, an error message is displayed: Error: Module './src/map/createMa ...

The Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

Tips for displaying text within an input field labeled "password" and then reverting back to a password display after entering text

I am working with a login form that includes a password field: <input type="password" name="password" id="password" value="Password" maxlength="40" required style="width: 130px; font-size: 10px;" /> Currently, the password field displays "******** ...

Is it possible to silence the other person's audio using livekit?

As a developer, I create meeting apps using React and livekit technology. I am looking for a reliable method to silence the audio of other participants in the virtual room. Any suggestions? ...

Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Nested Views in Angular UI Router

I have a specific structure set up like this: <div ui-view="main"> <!-- content is dynamically loaded here by AngularJS ui-router --> <aside ui-view="sidebar"> <!-- sidebar content is also populated by AngularJS ui-router --&g ...

Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the b ...

Executing polymorphism in Javascript without the use of OOP classes

In JavaScript or other object-oriented programming languages, polymorphism is achieved by creating different types. For instance: class Field {...} class DropdownField extends Field { getValue() { //implementation .... } } Imagine a library f ...

List out all the classes that implement an interface in Typescript

Greetings to all TypeScript enthusiasts! Here's a challenge I want to tackle: I aim to establish an interface -- let's name it IShape -- and define several classes (Rectangle, Circle, Triangle) that adhere to the IShape interface. Let's sa ...

AngularJS, perform an action on an HTML element within an ng-repeat directive once the user interface has been rendered

When using AngularJS to add a row to an HTML table by clicking an "Add row" button and using $scope.photos.push({}), you may encounter an issue when trying to trigger the file dialog of the new row's file input field. Is it possible to do this and if ...

Using the appropriate parameters is key: TS2345: The argument of type 'T' cannot be assigned to a parameter of type 'new() => any'

Struggling with Typescript 2, I am attempting to create a universal parser-method for database objects. Utilizing TypedJSON, I am encountering difficulties in correctly organizing the parameters. Here is part of my code: private static parseToInstance< ...

What is the syntax for defining a generic type in TypeScript when using the property name "type"?

Is there a way to declare a generic type GetAppActions where if T is equal to trigger, only the trigger data property is displayed, and vice versa? type GetAppActionType = 'trigger' | 'action' interface AppActionInputField {} type GetA ...

Unable to assign a value to a variable in JavaScript

Today, I delved into the world of JavaScript and decided to test my skills by creating a page that changes images when clicking on a div. Everything worked perfectly until I wanted to add an input element to specify how many steps to jump each time the but ...

The discord.js argument for startsWith should not be a standard regular expression

https://i.sstatic.net/UG79z.png What could be the reason behind this not working as expected? I am trying to check if a string starts with a number, and furthermore, I want it to handle multiple numbers. For instance, if the string starts with 1259823 the ...