我正在使用react和supabase。我编写了以下代码。我的工作是更新或创建。
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;
调用
createEditCabin
函数时,查询出现以下打字稿错误:
类型“PostgrestFilterBuilder
”缺少类型“PostgrestQueryBuilder ”中的以下属性:插入、更新插入、更新、删除(2739)
如何解决?
这是因为您正在重用 query 变量来选择和改变数据。您可以尝试分离逻辑,例如:
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;
};