TanStack Query (React Query): Handling HTTP Requests with EaseEntry 5 of 10
Conditional Queries with enabled
enabled: false stops a query from running automatically until a condition is met.
Notes
- While disabled, a query with no cached data stays
isPending, which would show a spinner forever. - Use
isLoading(isPending && isFetching) for spinners on disabled-capable queries; it's onlytruewhile a request actually runs. - Common uses: waiting for user input (search), waiting for another query's result (dependent queries), feature toggles.
- The course uses
enabled: searchTerm !== undefined: nothing loads until the first search, but an empty search ('') loads all events.
What / Why / When
- What
A switch for automatic fetching.
- Why
Avoids requests with missing or invalid parameters.
- When
The query depends on input or data that isn't available yet.
Code compare
const { data, isLoading } = useQuery({ queryKey: ["events", { search: searchTerm }], queryFn: ({ signal }) => fetchEvents({ signal, search: searchTerm }), enabled: searchTerm !== undefined,});If params returns undefined, the resource doesn't load and its status is 'idle'.
protected events = rxResource({ params: () => this.searchTerm(), // undefined → no request stream: ({ params: search }) => this.eventsService.getEvents({ search }),});Quick reference
| React | Angular |
|---|---|
enabled: condition | params returns undefined |
isLoading for spinners | isLoading() |
Disabled status: isPending | status() === 'idle' |