gpt4 book ai didi

reactjs - 带有 React Typescript 的 Firebase 9 : How do I change the querySnapshot types?

转载 作者:行者123 更新时间:2023-12-05 09:02:47 25 4
gpt4 key购买 nike

当我尝试从 firestore 保存我的查询快照时,它返回为 q: Query<DocumentData> ,我的查询快照是 querySnap: QuerySnapshot<DocumentData> .

文档数据类型为:[field: string]: any;而且我无法在不出现任何错误的情况下遍历它。

我的效果代码

useEffect(() => {
const fetchListings = async () => {
try {
// Get reference
const listingsRef = collection(db, "listings");

// Create a query
const q = query(
listingsRef,
where("type", "==", params.categoryName),
orderBy("timestamp", "desc"),
limit(10)
);

// Execute query
const querySnap = await getDocs(q);

let listings: DocumentData | [] = [];

querySnap.forEach((doc) => {
return listings.push({ id: doc.id, data: doc.data() });
});

setState((prevState) => ({ ...prevState, listings, loading: false }));
} catch (error) {
toast.error("Something Went Wront");
}
};

if (mount.current) {
fetchListings();
}

return () => {
mount.current = false;
};
}, [params.categoryName]);

有谁知道如何正确设置我的列表类型?

firestore 的列表类型应该是:

type GeoLocationType = {
_lat: number;
_long: number;
latitude: number;
longitude: number;
};

export type ListingsDataType = {
bathrooms: number;
bedrooms: number;
discountedPrice: number;
furnished: boolean;
geolocation: GeoLocationType;
imageUrls: string[];
location: string;
name: string;
offer: boolean;
parking: boolean;
regularPrice: number;
timestamp: { seconds: number; nanoseconds: number };
type: string;
userRef: string;
};

最佳答案

正如您所发现的,您可以简单地强制转换引用的类型:

const listingsRef = collection(db, "listings") as CollectionReference<ListingsDataType>;

但是,虽然这可行,但您可能会遇到 future 的问题,例如遇到意外的类型,或者您有其他无法很好地转换为 Firestore 的嵌套数据。

这是泛型类型的预期用途所在,您可以将 FirestoreDataConverter 对象应用于引用以在 DocumentData 和您选择的类型之间进行转换。这通常与基于类的类型一起使用。

import { collection, GeoPoint, Timestamp } from "firebase/firestore";

interface ListingsModel {
bathrooms: number;
bedrooms: number;
discountedPrice: number;
furnished: boolean;
geolocation: GeoPoint; // <-- note use of true GeoPoint class
imageUrls: string[];
location: string;
name: string;
offer: boolean;
parking: boolean;
regularPrice: number;
timestamp: Date; // we can convert the Timestamp to a Date
type: string;
userRef: string; // using a converter, you could expand this into an actual DocumentReference if you want
}

const listingsDataConverter: FirestoreDataConverter<ListingsModel> = {
// change our model to how it is stored in Firestore
toFirestore(model) {
// in this case, we don't need to change anything and can
// let Firestore handle it.
const data = { ...model } as DocumentData; // take a shallow mutable copy

// But for the sake of an example, this is where you would build any
// values to query against that can't be handled by a Firestore index.
// Upon being written to the database, you could automatically
// calculate a `discountPercent` field to query against. (like "what
// products have a 10% discount or more?")
if (data.offer) {
data.discountPercent = Math.round(100 - (model.discountedPrice * 100 / model.regularPrice))) / 100; // % accurate to 2 decimal places
} else {
data.discountPercent = 0; // no discount
}
return data;
},

// change Firestore data to our model - this method will be skipped
// for non-existant data, so checking if it exists first is not needed
fromFirestore(snapshot, options) {
const data = snapshot.data(options)!; // DocumentData
// because ListingsModel is not a class, we can mutate data to match it
// and then tell typescript that it is now to be treated as ListingsModel.
// You could also specify default values for missing fields here.
data.timestamp = (data.timestamp as Timestamp).toDate(); // note: JS dates are only precise to milliseconds
// remove the discountPercent field stored in Firestore that isn't part
// of the local model
delete data.discountPercent;
return data as ListingsModel;
}
}

const listingsRef = collection(db, "listings")
.withConverter(listingsDataConverter); // after calling this, the type will now be CollectionReference<ListingsModel>

这记录在以下地方:

关于reactjs - 带有 React Typescript 的 Firebase 9 : How do I change the querySnapshot types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70861528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com