TanStackT
TanStack2mo ago
7 replies
sacred-rose

Refactoring queries

I'm working on a big enterprise project that grew out of a startup. Just like any other startup, it has all the same problems—fast-growing, constantly changing requirements, tons of code, different architectural approaches, etc. With a growing codebase, I started to observe query key collisions, and I want to clean this mess up, as it's becoming harder to maintain and catch bugs. I was looking into 2 possible solutions:
1. query-key-factory
2. query options

To give you an example of the code, everywhere in the project we use custom hooks like this one:
export function useShiftPickupApprovals(params: GetShiftPickupApprovalsDto) {
  return useQuery({
    queryKey: ['schedules', 'shift-pickups', params],
    queryFn: () =>
      api.get<ShiftPickupApprovalsResponse>(
        `/schedules/tasks/${params.facilityId}/shift-requests`,
        { params }
      ),
    enabled: !!params.facilityId,
    placeholderData: keepPreviousData,
  });
}

export function useUpdateShiftAssignment() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (dto: UpdateScheduleAssignmentsDTO) =>
      api.post('/schedules/records', dto),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ['schedules'],
      });
    },
  });
}

Nowhere in the view layer do we use RQ directly, only these custom hooks. I wonder how to approach refactoring, not to f up things down the road. I tend to use query-key-factory over the query options approach, as I don't really see the benefits of using the latter one.
@TkDodo 🔮 Any valuable insights? Any piece of advice on how to approach this? And what are the pros/cons of the 2 approaches I've mentioned? And yes, I've read the docs and your Blog thoroughly, but still don't understand the query options approach and its benefits when using custom hooks.
Was this page helpful?