I save data on my database with an RLS feature for authenticated users who can only insert, update, and delete their data; this works well. When I save data on the database, I check if any data with that id exist; if it does,increase the quantity if it doesn't create on the database. This works great; however, if an authenticated user saves an item with an id on the database, another user cannot save the same data with the id on the database because it looks like a duplicate even though this is from another user. How can I combat this please?
if(user){
console.log(user)
//check if the object exists already on our database using the ID
const { data, error } = await supabaseClient
.from('cartItems')
.select()
.eq('id', uniqueId)
console.log('product widget', data)
if (data.length > 0) {
// if data exists get its quantity and add it to new quantity
const newQuantity = data[0].quantity + counter
//update the cart item on the database
const { error } = await supabaseClient
.from('cartItems')
.update({ quantity: newQuantity })
.eq('id', uniqueId)
if (error) {
// console any error we encounter along the way
console.log(error)
alert('Error adding the item to your wishlist')
} else {
// alert that we have added to our wishlist successfully
alert('item added successfully to wishlist')
}
} else {
// add a new item if the item is not available on our database
const { error } = await supabaseClient
.from('cartItems')
.insert(
{
id: uniqueId,
name,
price,
image_src: imageSrc,
image_alt: imageAlt,
quantity: counter
}
)
if (error) {
// console any error encountered
console.log(error)
alert('Error adding the item to your wishlist, 2nd part')
} else {
alert('item added to Wishlist')
}
}
if(error){
console.log(error, 'error checking if the cart item data exists already')
}
}