向 indexDB 添加值时出错

Getting an error when adding a value to indexDB

提问人:Richardson 提问时间:11/2/2023 最后编辑:Darren ZouRichardson 更新时间:11/3/2023 访问量:32

问:

当我尝试向 IndexedDB 键添加值时,我收到以下错误。我添加的对象是一个嵌套对象,但我认为我有一个流错误。我正在将 React 与 TypeScript 一起使用。

>向 IndexedDB 添加对象: DOMException: Failed to execute 'add' on 'IDBObjectStore': Evaluating the object store's key path does not generate a value

import { openDB } from 'idb';
import { ExternalNestedA, ExternalNestedB } from '../redux-store/app-types/firestoreTypesAndPredicates';

const useIndexDb = () => {
  const addNestedDocToIndexDb = async (programId: string, data: ExternalNestedA | ExternalNestedB) => {
    try {
      const db = await openDB('indexTestDB', 1, {
        upgrade(db) {
          if (!db.objectStoreNames.contains('data')) {
            db.createObjectStore('data', { keyPath: `${programId}` });
        },
      });

      const transaction = db.transaction('data', 'readwrite');
      const store = transaction.objectStore('data');

      await store.add({ programId: data });

      console.log('Object added to IndexedDB successfully.');
    } catch (error) {
      console.error('Error adding object to IndexedDB:', error);
    }
  };

  return { addNestedDocToIndexDb };
};

export default useIndexDb;

reactjs typescript 索引数据库

评论

1赞 Josh 11/5/2023
键路径为浏览器提供了一种访问对象并获取特定属性值的方法。当您使用键路径创建对象存储时,您是在告诉 indexedDB 要为 id 使用什么属性。在这里,您尝试添加一个对此属性没有值的对象。'${programId}'
0赞 Joshua Bell 11/11/2023
更具体地说,使用模板文本指定键路径的方式意味着键路径是传递给 addNestedDocToIndexDb 函数的变量的值,而存储的使用属性名称“programId”。如果调用 addNestedDocToIndexDb 将“abc”作为 programId 传递,则需要使用“abc”作为属性名称来存储值。您可能希望 keyPath 只是文本字符串“programId”,而不是扩展为其值的表达式,但很难从代码中分辨出来。programId

答: 暂无答案