-
-
Save a1300/eeb5b3978b444f9819e269263a416d0c to your computer and use it in GitHub Desktop.
To handle dependent queries in TanStack React Query (react-query), you typically want the second query to wait until the first query has completed and provided the necessary data. The key is to use the enabled
option in your second query, so it only runs when the first query is successful and its data is available.
Here’s how you can do it:
import { useQuery } from '@tanstack/react-query';
// First query
const { data: firstData, isLoading: loadingFirst } = useQuery({
queryKey: ['first'],
queryFn: fetchFirstData,
});
// Second query, only enabled when firstData is available
const { data: secondData, isLoading: loadingSecond } = useQuery({
queryKey: ['second', firstData?.id], // Use firstData as part of the key if relevant
queryFn: () => fetchSecondData(firstData.id),
enabled: !!firstData, // Only run when firstData exists
});
Explanation:
- The first query fetches some data.
- The second query is dependent on the data from the first query. It uses the
enabled
property to ensure it only runs whenfirstData
is available (i.e., after the first query has finished successfully). - This pattern ensures the second request waits for the first to complete.
References:
Let me know if you need a more detailed example!
use ref for performance gains:
Great question! To efficiently sync a user's interests (stored as a JS array) with your Drizzle/Postgres backend when they update their interests via a mutation, you should:
1. Data Model
Assume:
persons
table (id, name, ...)interests
table (id, name)person_interests
table (person_id, interest_id) — many-to-many relationship
2. Frontend Flow
- User sends the full, updated array of interests (e.g.
["music", "coding", "cooking"]
) when they save.
3. Backend Mutation Steps
a. Upsert interests
- For each interest in the array, ensure it exists in the
interests
table.- Use Drizzle’s
insert
withonConflictDoNothing
(or similar) to avoid duplicates.
- Use Drizzle’s
b. Fetch Interest IDs
- Retrieve all interest IDs for the submitted names.
c. Sync Person's Interests
- Fetch the current interests for the person from
person_interests
. - Compute:
- To Add: Interests in the new array but not in DB.
- To Remove: Interests in DB but not in the new array.
- Use Drizzle to insert new links and delete old ones.
Sample Drizzle Code
// 1. Upsert interests
await db.insert(interests).values(
newInterests.map(name => ({ name }))
).onConflictDoNothing(); // prevents duplicate interest names
// 2. Get interest IDs
const interestRecords = await db
.select({ id: interests.id, name: interests.name })
.from(interests)
.where(in(interests.name, newInterests));
const interestIdMap = Object.fromEntries(
interestRecords.map(rec => [rec.name, rec.id])
);
// 3. Get current user's interests
const currentLinks = await db
.select({ interest_id: person_interests.interest_id })
.from(person_interests)
.where(eq(person_interests.person_id, personId));
const currentInterestIds = new Set(currentLinks.map(l => l.interest_id));
const newInterestIds = new Set(Object.values(interestIdMap));
// 4. Compute changes
const toAdd = [...newInterestIds].filter(id => !currentInterestIds.has(id));
const toRemove = [...currentInterestIds].filter(id => !newInterestIds.has(id));
// 5. Add new links
if (toAdd.length > 0) {
await db.insert(person_interests).values(
toAdd.map(interest_id => ({
person_id: personId,
interest_id,
}))
);
}
// 6. Remove old links
if (toRemove.length > 0) {
await db.delete(person_interests)
.where(
and(
eq(person_interests.person_id, personId),
in(person_interests.interest_id, toRemove)
)
);
}
Why this approach?
- Efficient: Only adds/removes what's changed.
- Prevents duplicates.
- Handles many-to-many properly.
- Works with Drizzle and Postgres.
Tips
- Wrap in a transaction for atomicity.
- Validate input on the backend.
- You do not update interests themselves, just the linking table.
If your interests are not a separate table (i.e., you store them as a JSON array), the approach is simpler (just update the array), but you'll lose normalization, searchability, and de-duplication features.
Let me know if you want the code adapted for a different schema or want transaction handling!
https://github.com/marmelab/react-admin