@leather.io/query
v2.20.0
Published
Leather query
Downloads
1,528
Maintainers
Readme
@leather.io/queries
We use React Query
to fetch APIs and to manage the cache of the responses.
Code practices:
- Create custom hooks for queries, don't use plain
useQuery
in components. - Treat the query key like a dependency array. queryFn should receive same arguments as a queryKey.
- Use selectors to transform the data before usage. Example:
export const useTodosQuery = select =>
useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
select,
});
export const useTodosCount = () => useTodosQuery(data => data.length);
export const useTodo = id => useTodosQuery(data => data.find(todo => todo.id === id));
- Keep api layer separate from the queries (queryFn separate from useQueries). Example:
function fetchGroups(): Promise<Group[]> {
return axios.get('groups').then((response) => response.data)
}
// ✅ data will be `Group[] | undefined` here
function useGroups() {
return useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
}
// ✅ data will be `number | undefined` here
function useGroupCount() {
return useQuery({
queryKey: ['groups'],
queryFn: fetchGroups,
select: (groups) => groups.length,
})
}
- Structure your Query Keys from most generic to most specific. Example:
['todos', 'list', { filters: 'all' }][('todos', 'list', { filters: 'done' })][
('todos', 'detail', 1)
][('todos', 'detail', 2)];
- Optional: we might want to try the concept of query key factory: https://tkdodo.eu/blog/effective-react-query-keys#use-query-key-factories
Reference: https://tkdodo.eu/blog/practical-react-query