Issue encountered when initiating a Dexie transaction: TransactionInactiveError

Having an issue with a service function that syncs a json file to my Dexie IndexedDB database. I keep encountering the following error when starting the transaction:

Unhandled rejection: TransactionInactiveError: Transaction has already completed or failed
./node_modules/dexie/dist/dexie.mjs/Transaction.prototype._promise@http://localhost:9000/dist/bundle.js:4876:30
./node_modules/dexie/dist/dexie.mjs/Dexie.prototype._transaction@http://localhost:9000/dist/bundle.js:6488:35
./node_modules/dexie/dist/dexie.mjs/Dexie.prototype.transaction@http://localhost:9000/dist/bundle.js:6438:34
updateEDSMSector/<@http://localhost:9000/dist/bundle.js:169098:26
...
...

The error occurs right after the

console.log('extracted json', json);
statement (with the next console.log not executing). I am unsure of what the problem might be and would appreciate any guidance on how to debug this issue.

  static async updateEDSMSector(sector_number: number[], db: EDSMLayerDB) {
    const sector = await db.sectors.where('sector_number').equals(sector_number).first();
    console.log("Checking for EDSM updates for sector", sector);
    const updatedDate = sector.updatedDate;
    const [sx, sy, sz] = sector.sector_number;
    const jsonFilename = `edsm/${sx}/${sy}/${sx}_${sy}_${sz}.json.gz`;
    let res = await fetch(jsonFilename, {
      cache: 'no-cache',
      method: 'HEAD',
    });
    const lastModified = new Date(res.headers.get('Last-Modified'));
    console.log('updatedDate', updatedDate, 'lastModified', lastModified);
    if (!updatedDate || new Date(updatedDate) < lastModified) {
      res = await fetch(jsonFilename, {
        cache: 'no-cache',
        method: 'GET',
      });
      console.log('importing data');
      const json = JSON.parse(ungzip(new Uint8Array(await res.arrayBuffer()),
        {to: 'string'}));
      console.log('extracted json', json);
      await db.transaction('rw', db.sectors, db.systems, async () => {
        console.log('started transaction');
        await db.systems.where('sector').equals(sector.sector_number).delete();
        console.log('deleted old data');
        for (const system of json) {
          const {coords, ...rest} = system;
          const val = {...rest, ...coords};
          await db.systems.add(val);
        };
        console.log('Added systems');
        sector.updatedDate = new Date();
        await db.sectors.put(sector);
      });

      console.log('Finished adding system data');
    } else {
      console.log('Systems for sector', sector, 'already up-to-date.');
    }

  }

Answer №1

The problem arose when I tried to execute code asynchronously using the following snippet:

db.mytable.where(...).each((row) => { updateEDSMSector(row.sector_number, db) };

This code triggered a new transaction for each query result, leading to overlapping transactions due to asynchronous execution. To solve this issue, I modified the approach by fetching db.mytable.where().toArray() first and then iterating over the results. This modification allowed my updateEDSMSector calls to continue running asynchronously without causing conflicts with existing transactions.

Answer №2

After examining the code snippet provided, it appears to be a program designed for nodes. While Dexie is primarily intended for browsers, it can also run in node environments with the help of IndexedDBShim. In such cases, it is essential to refrain from using async/await keywords as IndexedDBShim may trigger its transaction prematurely.

To work around this issue, you have the option of transpiling your code to ES5 or refraining from using async/await altogether.

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

Ensure to verify within the ngOnInit function whether the checkbox has been selected

Hi everyone, I'm currently facing a situation where I have a list of checkboxes on one screen. When I select some checkboxes, they move to another screen and remain selected there. However, the issue is that when I try to use a button on the second sc ...

What is the best way to assign TypeScript interfaces to an Input field?

Suppose I have the following interface CardDetail: export interface CardDetail { name: string; type: string; logo?: string; What is the correct way to ensure that the @Input() decorators accept this type of data? import { CardDetail } from ' ...

Neglect TypeScript errors in project using yarn workspaces

While working on a repository with Yarn workspaces, I encountered an issue. When I use tsc --noEmit to perform type checking within the workspace folder, errors are appearing for packages stored in the top-level node_modules directory. ../../node_modules/ ...

Missing modules in electron application following the build process on a Mac device

Currently, I am working on a small Electron application that utilizes Vue and TypeScript. While running the app in development mode, everything functions properly. However, when I build the app using Electron Builder, certain modules seem to disappear. Spe ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

Can we modify the auto-import format from `~/directory/file` to `@/directory/file`?

I have a small issue that's been bugging me. I'm working on a project using Nuxt3 and Vscode. When something is auto-imported, Vscode uses the ~/directory/file prefix instead of the preferred @/directory/file. Is there an easy way to configure Vs ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...

The width of the Ion-slide is dynamically determined by the styling

After transitioning my Ionic 2 project to Ionic 3, I encountered issues with ion-slides which are affecting my app's functionality. Upon app loading, specific widths are being defined in the style tags on the slides, disrupting the intended styling. ...

Error: The function 'describe' has not been defined in the Karma jasmine angular2 environment

Struggling with writing tests using Jasmine and Karma in my Ionic project V2. All necessary packages have been added, but I'm still encountering the issue "describe is not defined". Can anyone offer assistance? Thank you. Here's my karma.conf.js ...

Having trouble capturing emitted events from a child component in Angular 2+?

I have a question as a beginner. I'm trying to send a message from the child component to the parent component but for some reason, it's not working. app.component.html <app-cart-component> [items]="rootItems" (outputItems)=&quo ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

What is the best way to ensure that dynamic routes from the server do not fail upon refreshing?

My application's permissions are dynamically received from the server. I have implemented a solution where I modify the router tree (using Router.config) before navigating to any item's URL in my navigation bar. Here is the function that sets the ...

Bring in the module for DecompressionStream

I'm encountering an issue in my React Typescript app where I am seeing the following error message: webpack compiled with 1 warning ERROR in src/App.tsx:30:21 TS2304: Cannot find name 'DecompressionStream'. 28 | const enc = new TextEncod ...

Can Vue props accept a generic type argument?

Currently, I have a basic component that is receiving the following props: props: { options: { type: Array as PropType<unknown[]>, default: () => [] }, labelKey: { type: String, default: "label" ...

How come I am unable to bring in an enum into my Angular 2 component?

In my project, I defined an enum inside the "country-details/enum" folder: export enum ConfigTypes { STAFF, PROD } When trying to import this enum into another component, I encountered a "cannot resolve symbol" error. It's worth mentioning that m ...

Building a Mobile App with Ionic 2, Cordova, and Typescript: Leveraging the Power

I'm currently developing an Ionic 2 application using Typescript. To set preferences, I want to utilize the cordova plugin https://github.com/chrisekelley/AppPreferences/. There are a couple of challenges I am facing. Despite thorough research onlin ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

Tips for positioning input fields and labels in both horizontal and vertical alignment

Below is the HTML code, and I want the tags to look like this: label1: input1 label2: input2 label3: input3 Instead, it currently looks like this: label1: input1 How can I modify the HTML to achieve the desired format? HTML: <div class=" ...

Merging JSON data with Arrays using TypeScript within the context of Ionic 3

Attempting to embed data as a string within an access modifier (public pieChartLabels) that is an array has been challenging. Despite successfully retrieving the expected data from the provider using console.log, integrating it with the modifiers has prove ...