I am using react and supabase. I have written the following code. I has job of updating or creating.
export const createEditCabin = async (newCabin: createCabinType, id?: number) => {
let imagePath = "";
let imageName = "";
if (typeof newCabin.image === "object") {
imageName = `${Math.floor(Math.random()) * 10}-${newCabin.image.name}`.replaceAll("/", "");
imagePath = `${supabaseUrl}/storage/v1/object/public/cabin-images/${imageName}`;
} else {
imagePath = newCabin.image
}
let query =supabase.from("Cabins");
// Create
if (!id) {
query = supabase.from("Cabins").insert([
{ ...newCabin, image: imagePath }
]);
}
// Edit
if (id) {
query = supabase.from("Cabins")
.update({ ...newCabin, image: imagePath })
.eq('id', id);
}
const { data, error } = await query.select().single();
return data;
When calling the createEditCabin
function, the following typescript error appears for query:
Type 'PostgrestFilterBuilder<any, any, null, "Cabins", unknown>' is missing the following properties from type 'PostgrestQueryBuilder<any, any, "Cabins", unknown>': insert, upsert, update, deletets(2739)
How can solve it?
It's because you are reusing query variable for select and mutating the data. You can try to separate the logic like:
export const createEditCabin = async (newCabin: createCabinType, id?: number) => {
let imagePath = "";
let imageName = "";
if (typeof newCabin.image === "object") {
imageName = `${Math.floor(Math.random() * 10)}-${newCabin.image.name}`.replaceAll("/", "");
imagePath = `${supabaseUrl}/storage/v1/object/public/cabin-images/${imageName}`;
} else {
imagePath = newCabin.image;
}
if (!id) {
const { data, error } = await supabase
.from("Cabins")
.insert([{ ...newCabin, image: imagePath }])
.select()
.single();
if (error) throw error;
return data;
}
if (id) {
const { data, error } = await supabase
.from("Cabins")
.update({ ...newCabin, image: imagePath })
.eq("id", id)
.select()
.single();
if (error) throw error;
return data;
}
return null;
};