'Invalidate queries, how to pass a variable (React Query)
When I execute onSettled within useMutation I want to pass a string.
In the beginning, I'm passing a string called top as the pageType but once I executed onSettled, I want to pass a different value (lottery) in the pageType
I want to do modify is the value('top' -> 'lottery') in the variable page in the get(`/api?token=${token}&page='top'` -> get(`/api?token=${token}&page='lottery'
I tried onSettled: () => queryCache.invalidateQueries(['campaign', {pageType: 'lottery']) but that didn't work.
Any idea how can I do it?
useCampaign:
const useCampaign = (token, id, page) =>
useQuery(
'campaign',
() =>
instance
.get(`/api?token=${token}&page=${page}`, {
headers: { 'id': id }
})
.then((res) => res),
{
retry: false,
}
)
index:
const { data } = useCampaign(
token ?? '',
campaignID ?? '',
'top' // here the value needs to be 'top'
)
const [lottery, lotteryInfo] = useMutation(
() =>
instance.post(
ENDPOINT,
{},
{
headers: { 'id': campaignID }
}
),
{
onSettled: () => queryCache.invalidateQueries('campaign')
// here I want to pass the value of 'lottery' instead of 'top'
}
)
Note: I'm using React Query 2.7.0.
Solution 1:[1]
Add page to your query key
const useCampaign = (token, id, page) => {
return useQuery(['campaign', page], () => {})
}
// Later in your useMutation
onSettled: () => queryCache.invalidateQueries(['campaign', 'top'])
Solution 2:[2]
invalidateQueries is not the right choice here. What you essentially want to do is update the pageType so that you can fetch some different data. This means the query keys should ideally be different. Here's how you can do that.
useCampaign:
const useCampaign = (token, id, page) =>
useQuery(
['campaign', page],
() =>
instance
.get(`/api?token=${token}&page=${page}`, {
headers: { 'id': id }
})
.then((res) => res),
{
retry: false,
}
)
index:
const [pageType, setPageType] = useState('top');
const { data } = useCampaign(
token ?? '',
campaignID ?? '',
pageType
)
const [lottery, lotteryInfo] = useMutation(
() =>
instance.post(
ENDPOINT,
{},
{
headers: { 'id': campaignID }
}
),
{
onSettled: () => setPageType('lottery')
}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prithwee Das |
| Solution 2 | Ankit Gupta |
