Adding an object with a composite key to an IndexedDB object store is not permitted as the key already exists within the store. This limitation occurs when attempting to add an entry

I am facing an issue with my objectStore where adding an object with the same productId but a different shopName triggers an error in the transaction showing:

ConstraintError: Key already exists in the object store.
. This is how I initialized the objectStore:

openRequest.onupgradeneeded = e => {
    // @ts-ignore
    db = e.target.result;
    const objectStore = db.createObjectStore('cart', {keyPath: ['productId', 'shopName']})
    console.log('Db set up')
}

This is how I add objects:

    function addProduct(product: CartProduct) {
        const pk = {productId: product.productId, shopName: product.shopName}

        const {transaction, objectStore, cursorRequest} = getIndexedDbTriplet();

        cursorRequest.onsuccess = e => {
            // @ts-ignore
            const cursor = e.target.result
            if (cursor) {
                if (cursor.primaryKey[0] === pk.productId && cursor.primaryKey[1] === pk.shopName) {
                    cursor.value.count++
                    cursor.update(cursor.value)
                    // @ts-ignore
                    console.log(`Found ${JSON.stringify(pk)} in db and updated`)
                    return
                }
                cursor.continue()
            }
            objectStore.add(product)
            transaction.oncomplete = () => console.log(`Added ${JSON.stringify(pk)} to db`)
        }

        // @ts-ignore
        transaction.onerror = e => console.log(`Transaction to add product failed: ${JSON.stringify(pk)} ${e.target.error}`)
    }
export class CartProduct {
    readonly productId: number
    readonly name: string
    readonly price: number
    readonly shopName: string
    readonly imageUri: string
    readonly weight: number
    readonly count = 1

    constructor(productId: number, name: string, price: number, shopName: string, imageUri: string, weight: number) {
        this.productId = productId
        this.name = name
        this.price = price
        this.shopName = shopName
        this.imageUri = imageUri
        this.weight = weight
    }
}
export function getIndexedDbTriplet() {
    const transaction = db.transaction('cart', 'readwrite')
    const objectStore = transaction.objectStore('cart')
    const cursorRequest = objectStore.openCursor()
    return {transaction, objectStore, cursorRequest};
}

All the code is within the same file.

Answer №1

The problem was resolved by substituting the add function call with the put function.

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

Navigating through nested objects using Rxjs

How to Extract Specific Attribute Values from Nested Objects Array using RxJS const obj = { name: 'campus', buildings: [ { name: 'building', floors: [ { name: 'floo ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

Choosing options using an enum in Angular 2

In my TypeScript code, I have defined an enum called CountryCodeEnum which contains the values for France and Belgium. export enum CountryCodeEnum { France = 1, Belgium = 2 } Now, I need to create a dropdown menu in my form using this enum. Each ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

When trying to reference a vanilla JavaScript file in TypeScript, encountering the issue of the file not being recognized

I have been attempting to import a file into TypeScript that resembles a typical js file intended for use in a script tag. Despite my efforts, I have not found success with various methods. // global.d.ts declare module 'myfile.js' Within the re ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

Is it possible to retrieve the second computed type in an overloaded method using TypeScript?

Looking for a solution to receive the second calculated type in an overload method using TypeScript type V1 = 'v1'; type V2 = 'v2'; type Versions = V1 | V2; async analyze(test: 'v1', data: number): Promise<void> ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

When attempting to access Firebase Storage with Angular, you may encounter the error message: "TypeError: app.storage

Having trouble connecting my Angular app to FireBase. The component appears blank and the Chrome console is showing a 'TypeError: app.storage is not a function'. Any ideas on what I might be doing wrong? Thanks in advance. ng --version Angular C ...

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

Establishing the data type for the state coming from the API

Whenever I try to add a new API response to the status, it shows as undefined. I need to filter out the incoming data from randomcocktail and then put it to use. Random.tsx import { useState, useEffect } from "react"; import { CocktailType } ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

Tips on selecting specific text from a drop-down menu

After struggling to find a solution for retrieving the text of a selected item from a dropdown, I decided to create a common directive. This directive would allow me to easily access the text for all dropdown items when used in my code. Below is the snippe ...