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

dependent-queries.md

49 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
userIdsQuery = injectQuery(() => ({
  queryKey: ['users'],
  queryFn: getUsersData,
  select: (users) => users.map((user) => user.id),
}))

// Then get the users' messages
usersMessages = injectQueries(() => ({
  queries:
    this.userIdsQuery.data()?.map((id) => ({
      queryKey: ['messages', id],
      queryFn: () => getMessagesByUsers(id),
    })) ?? [],
}))