-
Notifications
You must be signed in to change notification settings - Fork 0
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
useEffect内のdatafetchingに順序をつける #36
Comments
async/awaitを用いてdata fetchして返ってきたresponceをアプリ内のstateに入れたい時は、data fetchするサイクル内に入れる必要がある。 useEffect(() => {
// declare the async data fetching function
const fetchData = async () => {
// get the data from the api
const data = await fetch('https://yourapi.com');
// convert data to json
const json = await data.json();
return json;
}
// call the function
const result = fetchData()
// make sure to catch any error
.catch(console.error);;
// ❌ don't do this, it won't work as you expect!
setData(result);
}, []) But
|
data fetchingをする関数をuseEffectの外側で定義したい場合は、useCallbackを使う必要がある。 // declare the async data fetching function
const fetchData = useCallback(async () => {
const data = await fetch('https://yourapi.com');
setData(data);
}, [])
// the useEffect is only there to call `fetchData` at the right time
useEffect(() => {
fetchData()
// make sure to catch any error
.catch(console.error);;
}, [fetchData])
|
パラメーターが渡ってきた場合の挙動。 useEffect(() => {
let isSubscribed = true;
// declare the async data fetching function
const fetchData = async () => {
// get the data from the api
const data = await fetch(`https://yourapi.com?param=${param}`);
// convert the data to json
const json = await response.json();
// set state with the result if `isSubscribed` is true
if (isSubscribed) {
setData(json);
}
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);;
// cancel any future `setData`
return () => isSubscribed = false;
}, [param]) https://devtrium.com/posts/async-functions-useeffect#note-on-fetching-data-inside-useeffect |
useEffectが返却する型は、副作用を完全に無くすために、undefined又はfunctionでないといけない。
そのため、下記のように、useEffectに対してasyncを付けるとPromiseを返してしまうためNG。
Not
Promise文は関数宣言文を用意してから実行する必要がある。
But
参考
https://devtrium.com/posts/async-functions-useeffect
The text was updated successfully, but these errors were encountered: