admin管理员组文章数量:1220453
I'd like to implement useSWR in my web app and remove axios from the project, but I don't see how I can use SWR multiple times on the same page. I thought I could use two hooks:
const { userData, userError } = useSWR(url, fetcher)
const { coinData, coinError } = useSWR(url,fetcher)
but that doesn't work. (I guess you need to use { data, error }
)
This is the code I currently have, but I'd like to make another get request to my database with SWR.
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const { data, error } = useSWR(
`/${coinURL}`,
fetcher
);
if (error) {
return <div>failed</div>;
}
if (!data) {
return <div>Loading</div>;
}
return <div>{data.name}</div>;
What's the best way to make multiple requests on the same page with useSWR?
I'd like to implement useSWR in my web app and remove axios from the project, but I don't see how I can use SWR multiple times on the same page. I thought I could use two hooks:
const { userData, userError } = useSWR(url, fetcher)
const { coinData, coinError } = useSWR(url,fetcher)
but that doesn't work. (I guess you need to use { data, error }
)
This is the code I currently have, but I'd like to make another get request to my database with SWR.
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const { data, error } = useSWR(
`https://api.coingecko.com/api/v3/coins/${coinURL}`,
fetcher
);
if (error) {
return <div>failed</div>;
}
if (!data) {
return <div>Loading</div>;
}
return <div>{data.name}</div>;
What's the best way to make multiple requests on the same page with useSWR?
Share Improve this question asked Nov 6, 2021 at 16:02 Eric PezzuloEric Pezzulo 3992 gold badges7 silver badges21 bronze badges 1- 3 Does this answer your question? ES6/ES2015 object destructuring and changing target variable – brc-dd Commented Nov 6, 2021 at 20:45
2 Answers
Reset to default 12try
const { data : userData, error: userError } = useSWR(url, fetcher)
const { data : coinData, error: coinError } = useSWR(url,fetcher)
The issue is that you are re-using the same constant variable names. You can just store the result of useSWR
in an object:
const res1 = useSWR(..);
const res2 = useSWR(..);
And then reference each property like normal: res1.loading
, etc.
本文标签: javascriptuseSWR for mutiple requestsStack Overflow
版权声明:本文标题:javascript - useSWR for mutiple requests - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739288245a2156569.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论