Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-query useMutation when useQuery with parameters

Would someone advice me what is correct approach to update a data with useMutation when useQuery has parameters?

Lets assume we have this code:

const {data} = useQuery(["key", ["id1", "id2"]], methodWhichTakesThoseIds)

So the method methodWhichTakesThoseIds takes ["id1", "id2"] and returns some data from database. This data is an array of objects type like SomeModel[]. For eg. it could be:

[{name: "foo"}, {name:"bar"}]

All good, but now I want to update this data on screen and on database with useMutation

const [mutate] = useMutation(methodWhichUpdatesDataAndReturnsNewItem, {
        onSuccess: (data) => {
            queryCache.setQueryData(["key", ["id1", "id2"]], (old) => [...old, data]
            })
        }
    })

So now I added new item to database and the data in case should be: [{name: "foo"}, {name:"bar"}, {name:"newOne"].

All good again, but when I change the route and back again, the useQuery with only 2 IDs will fire again and useQuery returns data with only two element from database because it has only two IDs as paramters ["id1", "id2"].

If I'll set queryCache.setQueryData(["key", ["id1", "id2", data.id]], (old) => [...old, data] I'm still using original useQuery with only two IDs so changes won't reflect on screen.

I guess there are solutions like refetch data from server every time after update, but main question is"

What is the best approach to update data when useQuery has parameters - not only the key like useQuery("key", method) ?

like image 595
OMGImOut Avatar asked Jun 19 '26 11:06

OMGImOut


1 Answers

Assuming you don't need to cache all the fetch queries that take diff sets of IDs

so instead of this:

const { data } = useQuery(["key", ["id1", "id2"]], methodWhichTakesThoseIds)

do:

const fetchWrapper = (params) => () => methodWhichTakesThoseIds(params);
const { data } = useQuery(["key", 'fetchData'], fetchWrapper(["id1", "id2"]));

then after your mutation, you can simply call your onSuccess like this to update cache:

onSuccess: (data) => {
  queryCache.setQueryData(["key", "fetchData"], (old) => [...old, data];
}
like image 198
Shan Avatar answered Jun 23 '26 00:06

Shan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!