'Relational data in react-query

I have a REST api which has this endpoint for getting an assignment -

'/classes/<str:code>/assignments/<int:assignment_id>'

I have created a custom hook for querying an Assignment:

const getAssignment = async ({ queryKey }) => {
    const [, code, assignmentId] = queryKey
    const { data } = await api.get(`/classes/${code}/assignments/${assignmentId}`)
    return data
}

export default function useAssignment(code, assignmentId) {
    return useQuery(['assignment', code, assignmentId], getAssignment)
}

This works as expected, but is this the right way to deal with relational data in react-query?



Solution 1:[1]

code looks right to me. react-query doesn't have a normalized cache, just a document cache. So if you request assignments with a different query key, e.g. assignments for a user, they will be cache separately.

The straight forward approach to tackle this would then be to structure your query keys in a way that you can invalidate everything at the same time.

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 TkDodo