TanStackT
TanStack10mo ago
12 replies
dry-scarlet

Auto-refresh select function when Zustand state changes

Hello! I need help with an issue I'm facing when using TanStack Query with Zustand.

Current Situation


I'm fetching data with TanStack Query and then filtering it based on a state managed by Zustand. My selector function directly accesses the Zustand store internally:

// Selector function that directly accesses Zustand state
export const filteredTodosByStatus = (data: Todo[]) => {
  // Directly accessing Zustand state internally
  const status = useFilterStore.getState().status;
  
  if (status === 'all') return data;
  return data.filter(todo => 
    status === 'completed' ? todo.completed : !todo.completed
  );
};

// In the component
const { data: filteredTodos = [] } = useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  select: (data) => filteredTodosByStatus(data),
});


Problem Description


1. The filteredTodosByStatus function internally uses useFilterStore.getState().status to get the current filter state.
2. When the user changes the filter state by clicking a filter button, TanStack Query doesn't detect this change and doesn't re-run the
select
function.
3. As a result, the UI doesn't update to show the filtered data when the filter state changes.
Was this page helpful?