TanStackT
TanStack12mo ago
9 replies
wispy-olive

Understanding Query Key Objects

I just started using react-query and see most examples with simple query keys containing a single value.
Let's say I have the following:
type Colors = {
  blue: boolean;
  green: boolean;
  red: boolean;
};

type Square = {
  id: number;
  color: 'blue' | 'green' | 'red'
};


Then if I want to fetch all squares that are either blue OR red would I do
const useSquaresQuery = (colors: Colors) => {
  return useQuery({
    queryKey: ['square', colors],
    queryFn: () => fetchSquares(colors)
  });
}
...
const blueRedSquares = useSquaresQuery({
  blue: true,
  red: true
});

does this store all color combinations in their own query?

And is this the same if I have more filters?
type Size = 'big' | 'small';
type Filters = {
  colors: Colors
  size: Size
}
const useSquaresQuery = (filters: Filters) => {
  return useQuery({
    queryKey: ['square', filters],
    queryFn: () => fetchSquares(filters)
  });
}
Was this page helpful?