I'm using this piece of code (generated with chatGPT) This creatd a database with a datastore and adds some users to it with keypath userId. Then I try to find one of the users I just added to the store. But the user can't be found..
let db;
// Open the database
const openRequest = indexedDB.open('chatlog', 2);
openRequest.onupgradeneeded = function(e) {
db = e.target.result;
console.log('running onupgradeneeded');
if (!db.objectStoreNames.contains('trackinglist')) {
db.createObjectStore('trackinglist', {
keyPath: ['userId']
});
}
};
openRequest.onsuccess = function(e) {
db = e.target.result;
console.log('Database running...');
};
openRequest.onerror = function(e) {
console.log('Database error!');
console.dir(e);
};
// Function to create the tracking list and add users
function createTrackingList() {
const store = db.transaction(['trackinglist'], 'readwrite').objectStore('trackinglist');
const trackingList = [
{ userId: 727027, name: "John Doe", profileID: 0 },
{ userId: 727028, name: "Jane Doe", profileID: 1 }
];
trackingList.forEach((trackedUser) => {
const request = store.add(trackedUser);
request.onerror = (e) => {
console.log(e);
};
});
}
function clearTrackingList(){
const store = db.transaction(['trackinglist'], 'readwrite').objectStore('trackinglist');
store.clear();
}
// Function to get a tracked user
function getTrackedUser() {
const store = db.transaction(['trackinglist'], 'readonly').objectStore('trackinglist');
const userIdToGet = 727027;
const request = store.get(userIdToGet);
request.onsuccess = function(event) {
const user = event.target.result;
if (user) {
console.log("User found:", user);
} else {
console.log("User not found.");
}
};
request.onerror = function() {
console.error("Error getting user");
};
}
but no user is returned... what am I doing wrong?