4

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) ?

1 Answer 1

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.