INSERT failing on a Supabase table when it seems like I have done everything correctly, I need some help!
I have created a table in Supabase called "cart" where I will be storing all the user's carts. The table right now has only 1 policy and it's the INSERT policy "Enable insert for authenticated users only" that is on the right side when you click to create a new policy.
I checked GPT and it says that right now all the policy does is check to see if a user is authenticated and if they are the policy will allow the insert.
But when I try to insert while being authenticated I get this error in the console:
Failed to add item to cart:
code: "42501"
details: null
hint: null
message: 'new row violates row-level security policy for table "cart"'
Failed to add item to cart:
My policy:
alter policy "Enable insert for authenticated users only"
on "public"."cart"
to authenticated
with check ( true );
I have checked and can see that the user is authenticated.
Here is my function that should insert the data:
export async function addToCart(
product_id: string,
user_id: string,
quantity: number,
size: string,
) {
try {
const { data, error } = await supabase
.from("cart")
.insert([
{
product_id: product_id,
user_id: user_id,
quantity: quantity,
size: size
}
]);
if (error) {
console.error("Failed to add item to cart:", error);
return null;
}
return data;
} catch (error: any) {
console.error("Something went wrong", error.message);
return;
}
}
And here is how I grab the user's data:
useEffect(() => {
const getUser = async () => {
const { data, error } = await supabase.auth.getUser();
if (error) {
console.error("Unable to get user details", error);
return;
}
setUser(data?.user || null);
};
getUser();
// Listen for authentication state changes
const { data: authListener } = supabase.auth.onAuthStateChange((_event, session) => {
setUser(session?.user || null);
});
// Cleanup to remove listener when component unmounts
return () => {
authListener?.subscription?.unsubscribe();
};
}, []);
Here is the function that handles adding the items to the cart if the user is authenticated, and if the user is not authenticated I run a different function that just adds the selected item to sessionStorage:
const handleClick = async () => {
if (!selectedSize) {
setSizeError(true);
return;
}
if (user) {
console.log("USER ID:", user.id);
const result = await addToCart(product.id, user?.id, quantity, selectedSize);
if (result) {
console.log("Item added to cart:", result);
} else {
console.error("Failed to add item to cart.");
}
} else {
addToCartWithoutAuth();
}
};
I don't know what to do now, what is causing the data to be rejected and not be inserted?