Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

將抓 api 的邏輯都改用 Tanstack Query #4

Open
QzCurious opened this issue Feb 18, 2024 · 2 comments
Open

將抓 api 的邏輯都改用 Tanstack Query #4

QzCurious opened this issue Feb 18, 2024 · 2 comments

Comments

@QzCurious
Copy link
Contributor

以不熟悉 React 的人 來說, 我會建議先使用 useEffect, useState 來抓 api,等有熟悉度之後再來轉 Tanstack Query

我們可以先聊聊看要不要現在就朝 Tanstack Query 走,不用馬上動工

@QzCurious
Copy link
Contributor Author

QzCurious commented Feb 19, 2024

昨天有解析一下為什麼不能將抓 api 的邏輯用 useMemo 來實作就好:

之前有說到,useMemo 其實是 "衍生" 的狀態,而抓 api 是會有多種狀態、多個階段:

  1. 尚未打 api,state 會是 idledata 會是 undefined
  2. 打 api,這時 state 應該為 loadingdata 仍是 undefined
  3. api 成功回傳,state 轉為 successeddata 就會有東西

這樣就能明顯看出我們至少需要

// 儲存狀態
const [state, setState] = useState('idle')
const [data, setData] = useState()

// 觸發 fetch
useEffect(() => { fetch(...) }, [])

如果只用 useMemo 就無法表示出這麼多狀態

@DoubleTian-tw
Copy link
Owner

useMemo只會有"一個"狀態階段也就是"衍生",當有"多個"階段就不適合使用,例如提到的fetch api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants