can fetch data from web

This commit is contained in:
Yifei Hu 2024-07-08 16:46:15 +08:00
parent 2ca85ad015
commit 676e2231b0
5 changed files with 289 additions and 25 deletions

View file

@ -9,38 +9,32 @@ interface NewsItem {
summary: string;
}
const hardcodedNews: NewsItem[] = [
{
"id": "ed701716-e443-5804-aaa9-99e7e04c33e2",
"title": "胖东来迅速应对擀面皮事件,展现企业责任感",
"summary": "胖东来商贸集团因擀面皮加工场所卫生问题迅速采取行动关闭相关档口并展开调查。确认问题后公司对举报顾客奖励10万元并对购买问题产品的顾客进行退款和补偿总计883.3万元。同时,胖东来辞退相关责任人,解除与涉事商户的合作,并制定改进计划以确保食品安全。公众对其快速透明的处理措施表示赞赏,认为其展现了企业的社会责任感。"
},
{
"id": "869d933c-e186-51b0-a225-edc2d338b6fa",
"title": "姜萍晋级全球数学竞赛决赛引发质疑",
"summary": "17岁中专生姜萍在2024阿里巴巴全球数学竞赛中晋级决赛但其成绩真实性受到质疑。北京大学教授袁新意指出她在校内月考成绩仅为83分建议姜萍通过直播讲解竞赛题目或接受数学教授面试来证明实力。涟水县教育体育局确认了月考成绩的真实性但质疑声仍未平息。姜萍的成功故事激励了许多人凸显了教育公平和知识改变命运的重要性。"
},
];
const NewsPage = () => {
const [news, setNews] = useState<NewsItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadNews = async () => {
const fetchNews = async () => {
try {
await new Promise(resolve => setTimeout(resolve, 500));
setNews(hardcodedNews);
console.log("Fetching news...");
const response = await fetch("https://raw.githubusercontent.com/TomorrowMC/newsDemoData/main/data.json");
console.log("Response status:", response.status);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Fetched data:", data);
setNews(data);
} catch (error) {
console.error("Error loading news:", error);
setError("Failed to load news. Please try again later.");
console.error("Error fetching news:", error);
setError(`Failed to load news. Error: ${error instanceof Error ? error.message : String(error)}`);
} finally {
setLoading(false);
}
};
loadNews();
fetchNews();
}, []);
return (
@ -56,8 +50,9 @@ const NewsPage = () => {
<p className="text-black/70 dark:text-white/70 text-sm">Loading news...</p>
</div>
) : error ? (
<div className="flex flex-row items-center justify-center min-h-screen">
<p className="text-red-500 text-sm">{error}</p>
<div className="flex flex-col items-center justify-center min-h-screen">
<p className="text-red-500 text-sm mb-2">Failed to load news.</p>
<p className="text-red-500 text-xs">{error}</p>
</div>
) : (
<div className="flex flex-col pt-16 lg:pt-24">