Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

dependent-queries.md

48 lines1.1 KB

// Get the user
userQuery = injectQuery(() => ({
  queryKey: ['user', this.email()],
  queryFn: this.getUserByEmail,
}))

// Then get the user's projects
projectsQuery = injectQuery(() => ({
  queryKey: ['projects', this.userQuery.data()?.id],
  queryFn: this.getProjectsByUser,
  // The query will not execute until the user id exists
  enabled: !!this.userQuery.data()?.id,
}))

Dynamic parallel query - injectQueries can depend on a previous query also, here's how to achieve this:

// Get the users ids
userIds = injectQuery(() => ({
  queryKey: ['users'],
  queryFn: getUserData,
  select: (users) => users.map((user) => user.id),
}))

// Then get the users messages
userQueries = injectQueries(() => ({
  queries: (this.userIds() ?? []).map((userId) => ({
    queryKey: ['user', userId],
    queryFn: () => getUserById(userId),
  })),
}))