useEffect
觸發 API 請求setIsLoading(true)
setBlogs(data)
,同時 setIsLoading(false)
setError(err.message)
,同時 setIsLoading(false)
Home.js
import { useEffect, useState } from "react";
import BlogList from "./BlogList";
const Home = () => {
const [blogs, setBlogs] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
setTimeout(() => {
fetch("http://localhost:8000/blogs")
.then(res => {
if (!res.ok) {
throw Error("無法讀取資料來源");
}
return res.json();
})
.then(data => {
setIsLoading(false);
setBlogs(data);
setError(null);
})
.catch(err => {
setIsLoading(false);
setError(err.message);
})
}, 100);
}, [])
return (
<div className="home">
{error && <div>{ error }</div>}
{ isLoading && <div>資料載入中...</div> }
{blogs && <BlogList blogs={blogs} />}
</div>
);
}
export default Home;
const [isLoading, setIsLoading] = useState(true);
表示「資料是否還在載入中」
.then(data => {
setIsLoading(false);
setBlogs(data);
setError(null);
})
setIsLoading(false);
setBlogs(data);
setError(null);
return{ isLoading && <div>資料載入中...</div> }
註:setTimeout(() =>{{(…)}, 100)
主要是延長資料讀取的時間,方便使用者知道目前狀態
瀏覽器執行畫面
const [error, setError] = useState(null);
用來存放錯誤訊息
null
,代表沒有錯誤setError(err.message);
if (!res.ok) { throw Error("無法讀取資料來源") }
.catch
接收註:res.ok
是 Response 物件內建的屬性,幫忙檢查狀態碼是不是 200–299 之間
.catch(err => {
setIsLoading(false);
setError(err.message);
})
.catch(err => {...})
.catch
,把錯誤物件傳進來setIsLoading(false);
setError(err.message);
return{ error && <div>{ error }</div> }
瀏覽器執行畫面