[英]How do I get data from Firebase collection using NextJs API, Firebase Firestore, axios and TypeScript?
我在 NextJS 13 中使用 api 路由,像這樣從 Firebase 獲取數據( api/locations.tsx
):
import { db } from "../../firebase";
import { collection, getDocs } from "firebase/firestore";
import type { NextApiRequest, NextApiResponse } from "next";
const Locations = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const locationsSnapshot = await getDocs(collection(db, "locations"));
const locationsData = locationsSnapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
}));
res.status(200).json({ locationsData });
} catch {
res.status(400).end();
}
};
export default Locations;
然后我有一個組件Locations.tsx
,我試圖將位置存儲在locations
state object 中,如下所示:
import { useEffect, useState } from "react";
import Link from "next/link";
import {
Container,
Content,
Main,
StyledLink,
Title,
} from "../components/sharedstyles";
import axios from "axios";
export type LocationData = {
film: string;
imdbId: string;
location?: string;
scene?: string;
coords: [number, number];
}[];
type GetLocationResponse = { data: { locationsData: LocationData[] } };
export default function About() {
const [locations, setLocations] = useState([]);
const getLocations = async () => {
// Fetch locations data from locations endpoint and return location data
const res = await axios.get<GetLocationResponse>("/api/locations");
return res.data.locationsData;
};
useEffect(() => {
setLocations(getLocations());
}, []);
return (
<Container>
<Main>
<Title>Locations</Title>
<Content>
<ul>
{locations?.map(({ location }) => (
<li>{location}</li>
))}
</ul>
</Content>
<Link href="/" passHref legacyBehavior>
<StyledLink>← Home</StyledLink>
</Link>
</Main>
</Container>
);
}
但我收到錯誤Property 'locationsData' does not exist on type 'GetLocationResponse'.
即使我嘗試將“locationsData”添加到我的類型定義中type GetLocationResponse = { data: { locationsData: LocationData[] } };
誰能告訴我為什么會出現此錯誤以及如何解決? 請和謝謝!
您的前端需要一個帶有data
屬性的響應 object:
type GetLocationResponse = { data: { locationsData: LocationData[] } };
但是您的后端正在發送 object 只有一個屬性locationsData
:
res.status(200).json({ locationsData });
也許您希望前端的期望通過刪除data
屬性來匹配后端發送的內容:
type GetLocationResponse = { locationsData: LocationData[] };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.