HuolalaTech / react-query-kit

🕊️ A toolkit for ReactQuery that make ReactQuery hooks reusable and typesafe
MIT License
355 stars 11 forks source link

Primary Key should accepts arrays #36

Closed MiltonAkash closed 1 year ago

MiltonAkash commented 1 year ago

We manage a heirarchy of things like below so invalidating becomes easier. React query kit is awesome but the primary key being a string prevents implementation of heirarichal key thing. Should we add or any other workaround ???

const todoKeys = {
  all: ['todos'] as const,
  lists: () => [...todoKeys.all, 'list'] as const,
  list: (filters: string) => [...todoKeys.lists(), { filters }] as const,
  details: () => [...todoKeys.all, 'detail'] as const,
  detail: (id: number) => [...todoKeys.details(), id] as const,
}
liaoliao666 commented 1 year ago

There are no plans to accept arrays as primaryKey, but you can implement it as belown. This is also very simple.

const postScope = 'posts:'

const usePostList = createQuery({
  primaryKey: `${postScope}list`
})

const usePostDetail = createQuery({
  primaryKey: `${postScope}detail`
})

// invalidate all queries within post scope
queryClient.invalidateQueries({
  predicate(query) {
    return query.queryKey[0].startWidth(postScope)
  },
})
liaoliao666 commented 1 year ago

Or organize queries in a object.


const postQueries = {
  useList: createQuery({
    primaryKey: `posts:list`,
  }),
  useDetail: createQuery({
    primaryKey: `posts:detail`,
  }),
}

Object.values(postQueries).forEach(fn =>
  queryClient.invalidateQueries({ queryKey: fn.getKey() })
)
``