[英]How to use custom react query hook twice in the same component?
我有一個自定義鈎子,用於使用 useQuery 獲取數據。 鈎子工作正常,沒有問題。
const getData = async (url) => {
try{
return await axios(url)
} catch(error){
console.log(error.message)
}
}
export const useGetData = (url, onSuccess) => {
return useQuery('getData', () => getData(url), {onSuccess})
}
但是,如果我在組件中調用此鈎子兩次,即使使用不同的 URL,它也只會從第一次調用中獲取數據。 (忽略評論錯字,這是故意的)
我的組件中的調用:
const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`)
const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)
在這種情況下,當我 console.log forumPost 時,它是評論數組而不是論壇帖子,即使我傳遞的是不同的端點。
我怎樣才能使用這個鈎子兩次來獲取不同的數據? 可能嗎? 我知道我可以只調用並行查詢,但如果可能的話,我想使用我的鈎子。
由於useQuery
基於queryKey
緩存,因此在該名稱中使用 URL
const getData = async(url) => { try { return await axios(url) } catch (error) { console.log(error.message) } } export const useGetData = (url, onSuccess) => { return useQuery('getData' + url, () => getData(url), { onSuccess }) } //........ const { data: commentss, isLoading: commentsIsLoading } = useGetData(`/comments/${params.id}`) const { data: forumPost, isLoading: forumPostIsLoading } = useGetData(`/forum_posts/${params.id}`)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.