跳至主要内容

[note] react SWR

常見問題

isValidation 和 isLoading 的差別

在 SWR 中,雖然可以使用 !error && !data 來作為 isLoading 的狀態,但 useSWR 本身也會回傳 isValidating。這兩個乍看之下雖然好像很像,但實際上 isValidating 是只要有發出 API 請求的話,isValidating 都會從 false 變成 true,請求結束後才在變回 false;而透過 error 和 data 組出來的 isLoading 則不太一樣,它只有在一開始還沒向 API 發送過請求時,data 和 error 都是空的是才會是 true,一旦拉過資料後它的狀態就會變成 false,未來即使再次發送 API 請求拉資料,它的狀態仍然會一直是 false,而不會先變成 true 才又變回 false。

Development

  • 在開發時透過 yarn link 在個人專案中引用到 swr 打包好的檔案
  • 由於使用 swr 時,需要確保 swr 的 react 版本和專案中的 react 版本是一樣的,因此同樣需要透過 link 的方式,確保兩個專案使用的是相同的 react 套件
warning

npm cli 同樣有提供 link 的功能,但切記不要在同一個專案中同時使用 npm 和 yarn。由於 swr 是使用 yarn 來做套件的管理,因此這裡我們也是使用 yarn 提供的 link。

# 針對 swr 的專案,以 swr > 做為 prefix
# 針對想使用 swr 的專案,以 project > 做完 prefix

git clone git@github.com:vercel/swr.git
$ swr > git co 1.0.1 # checkout 到特定版本
$ swr > yarn # 安裝 dependency
$ swr > yarn build # 打包專案
$ swr > yarn register # 在根目錄建立 swr 和 react 的 link


$ project > yarn link swr # 使用根目錄的 swr 的 link
$ project > yarn link react # 使用根目錄的 react 的 link(確保 react 版本一致)

$ swr > yarn watch # 可以直接修改 swr 的專案看到對應的改變

接著,可以直接修改 swr 的專案,回到 project 中看到對應的改變:

diff --git a/src/use-swr.ts b/src/use-swr.ts
index b2f0a82..ff8757c 100644
--- a/src/use-swr.ts
+++ b/src/use-swr.ts
@@ -32,6 +32,8 @@ export const useSWRHandler = <Data = any, Error = any>(
fn: Fetcher<Data> | null,
config: typeof defaultConfig & SWRConfiguration<Data, Error>
) => {
+ console.log('hello swr')
+
const {
cache,
compare,