无法存储数据索引数据库(无法在"IDBObjectStore"上执行"add":评估对象存储的键路径未生成值)



所以我创建了一个索引数据库,然后打算存储从api响应中获取的数据。但有一个错误,我试图检查响应中的数据是否输入以及结果是否输入,但它仍然出现了错误,并尝试将方法更改为put((。

错误

**Uncaught (in promise) DOMException: Failed to execute 'add' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.**

指数

const playerDetails = ShowPlayerDetails();
const savePlayerButton = document.getElementById("savePlayerButton");
savePlayerButton.addEventListener("click", event => {
playerDetails.then(response => {
dbInsertPlayer(response);
});
});

索引数据库

const idbPromised = idb.open("player-favourite-list", 1, upgradeDb => {
if(!upgradeDb.objectStoreNames.contains("players")){
upgradeDb.createObjectStore("players", {autoIncrement: true});
}
});
const dbInsertPlayer = playerData => {
return new Promise((resolve, reject) => {
idbPromised.then(db => {
const transaction = db.transaction("players", "readwrite");
console.log(playerData);
return transaction.objectStore("players").put(playerData);
})
.then(transaction => {
if(transaction.complete){
resolve(true);
}
})
.catch(error => {
reject(error);
});
});
}

FetchAPI

function ShowPlayerDetails(){
return new Promise ((resolve, reject) => {
let urlParams = new URLSearchParams(window.location.search);
let idParam = urlParams.get("id");
FetchAPI(`${BASE_URL}players/${idParam}`)
.then(response => {
const {name, nationality, countryOfBirth, dateOfBirth, position} = response;
document.getElementById("player-name").innerHTML = name;
document.getElementById("player-data").innerHTML = `
<ul class="collection">
<li class="collection-item">Name : ${name}</li>
<li class="collection-item">Nationality : ${nationality}</li>
<li class="collection-item">Country Of Birth : ${countryOfBirth}</li>
<li class="collection-item">Date Of Birth : ${dateOfBirth}</li>
<li class="collection-item">Position : ${position}</li>
</ul>`;
resolve(response);
})
.catch(error => reject(error));
})
}

我的目标是将响应数据输入indexeddb,然后在其他时间显示它。

API响应

countryOfBirth: "Senegal"
dateOfBirth: "1992-04-10"
firstName: "Sadio"
id: 3626
lastName: null
lastUpdated: "2020-08-13T03:13:10Z"
name: "Sadio Mané"
nationality: "Senegal"
position: "Attacker"
shirtNumber: null

所以我在对象存储中添加了autoIncrement和keyPath,不要忘记通过存储浏览器删除数据库或升级当前索引数据库版本。

代码

const idbPromised = idb.open("player-favourite-list", 1, upgradeDb => {
if(!upgradeDb.objectStoreNames.contains("players")){
upgradeDb.createObjectStore("players", {keyPath: "Id", autoIncrement: true});
}
});

异常参考MDN索引数据库文档

相关内容

  • 没有找到相关文章

最新更新