Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(frontend): load lists at once on page open, debounce only user input (#127065)

Paul D'Ambra02102b70d693
diff --git a/frontend/src/scenes/approvals/approvalsLogic.test.ts b/frontend/src/scenes/approvals/approvalsLogic.test.ts
new file mode 100644
index 000000000000..2681ca460a61
--- /dev/null
+++ b/frontend/src/scenes/approvals/approvalsLogic.test.ts
@@ -0,0 +1,51 @@
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import api from 'lib/api'
+import { userLogic } from 'scenes/userLogic'
+
+import { initKeaTests } from '~/test/init'
+import { AvailableFeature, ChangeRequestState } from '~/types'
+
+import { approvalsLogic } from './approvalsLogic'
+
+describe('approvalsLogic', () => {
+ let listGet: jest.SpyInstance
+
+ const changeRequestRequests = (): string[] =>
+ listGet.mock.calls.map(([url]) => String(url)).filter((url) => url.includes('/change_requests/'))
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ initKeaTests()
+ listGet = jest.spyOn(api, 'get').mockResolvedValue({ results: [], count: 0 })
+ userLogic.actions.loadUserSuccess({
+ ...MOCK_DEFAULT_USER,
+ organization: {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: [{ key: AvailableFeature.APPROVALS, name: 'Approvals' }],
+ },
+ })
+ })
+
+ afterEach(() => {
+ listGet.mockRestore()
+ jest.useRealTimers()
+ })
+
+ it.each<[string, (logic: ReturnType<typeof approvalsLogic.build>) => Promise<void>]>([
+ ['the list opens', async (logic) => void logic.mount()],
+ [
+ 'the state filter changes',
+ async (logic) => {
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(1000)
+ listGet.mockClear()
+ logic.actions.setFilters({ state: ChangeRequestState.Applied })
+ },
+ ],
+ ])('sends the change request list request at once when %s', async (_, act) => {
+ await act(approvalsLogic())
+
+ expect(changeRequestRequests()).toHaveLength(1)
+ })
+})
diff --git a/frontend/src/scenes/approvals/approvalsLogic.tsx b/frontend/src/scenes/approvals/approvalsLogic.tsx
index e4c57c5a1bfc..67d5ec40e6ce 100644
--- a/frontend/src/scenes/approvals/approvalsLogic.tsx
+++ b/frontend/src/scenes/approvals/approvalsLogic.tsx
@@ -135,8 +135,6 @@ export const approvalsLogic = kea<approvalsLogicType>([
return { changeRequests: [], changeRequestsCount: 0 }
}
- await breakpoint(300)
-
const actualUrl =
url ||
`api/projects/${values.currentTeamId}/change_requests/?${new URLSearchParams({
diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
index b5fdadf244fd..2d26680702c1 100644
--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
@@ -131,6 +131,52 @@ describe('cohortsSceneLogic', () => {
})
})
+ describe('request timing', () => {
+ let listCohorts: jest.SpyInstance
+
+ beforeEach(() => {
+ logic.unmount()
+ jest.useFakeTimers()
+ listCohorts = jest.spyOn(api.cohorts, 'listPaginated').mockResolvedValue({ count: 0, results: [] })
+ })
+
+ afterEach(() => {
+ listCohorts.mockRestore()
+ jest.useRealTimers()
+ })
+
+ it.each<[string, Record<string, string>]>([
+ ['a bare URL', {}],
+ ['a search in the URL', { search: 'paying' }],
+ ])('sends one request at once when the page opens on %s', async (_, searchParams) => {
+ router.actions.push(urls.cohorts(), searchParams)
+ logic = cohortsSceneLogic()
+ logic.mount()
+
+ expect(listCohorts).toHaveBeenCalledTimes(1)
+
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(listCohorts).toHaveBeenCalledTimes(1)
+ })
+
+ it('waits for typing in the search box to pause, then sends one request', async () => {
+ router.actions.push(urls.cohorts())
+ logic = cohortsSceneLogic()
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(1000)
+ listCohorts.mockClear()
+
+ logic.actions.setCohortFilters({ search: 'pay', page: 1 })
+ logic.actions.setCohortFilters({ search: 'paying', page: 1 })
+ await jest.advanceTimersByTimeAsync(299)
+ expect(listCohorts).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(listCohorts).toHaveBeenCalledTimes(1)
+ expect(listCohorts).toHaveBeenCalledWith(expect.objectContaining({ search: 'paying' }))
+ })
+ })
+
describe('cohort operations', () => {
it('can delete a cohort', async () => {
// Wait for initial load
diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
index 80c333ca352c..f2530c93a31a 100644
--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.ts
@@ -99,8 +99,10 @@ export interface cohortsSceneLogicActions {
}
setCohortFilters: (
filters: Partial<CohortFilters>,
- replace?: boolean
+ replace?: boolean,
+ debounce?: boolean
) => {
+ debounce: boolean
filters: Partial<CohortFilters>
replace: boolean | undefined
}
@@ -143,7 +145,11 @@ export const cohortsSceneLogic = kea<cohortsSceneLogicType>([
actions: [exportsLogic, ['startExport']],
})),
actions(() => ({
- setCohortFilters: (filters: Partial<CohortFilters>, replace?: boolean) => ({ filters, replace }),
+ setCohortFilters: (filters: Partial<CohortFilters>, replace?: boolean, debounce: boolean = true) => ({
+ filters,
+ replace,
+ debounce,
+ }),
deleteCohort: (cohort: Partial<CohortType>) => ({ cohort }),
exportCohortPersons: (id: CohortType['id'], columns?: string[]) => ({ id, columns }),
setCohortSorting: (sorting: Sorting | null) => ({ sorting }),
@@ -284,8 +290,10 @@ export const cohortsSceneLogic = kea<cohortsSceneLogicType>([
return () => clearTimeout(timerId)
}, 'pollTimeout')
},
- setCohortFilters: async (_, breakpoint) => {
- await breakpoint(300)
+ setCohortFilters: async ({ debounce }, breakpoint) => {
+ if (debounce) {
+ await breakpoint(300)
+ }
actions.loadCohorts()
},
deleteCohort: async ({ cohort }) => {
@@ -367,7 +375,11 @@ export const cohortsSceneLogic = kea<cohortsSceneLogicType>([
filtersFromUrl.created_by_id = parseInt(created_by_id)
}
- actions.setCohortFilters({ ...DEFAULT_COHORT_FILTERS, ...filtersFromUrl }, true)
+ const nextFilters = { ...DEFAULT_COHORT_FILTERS, ...filtersFromUrl }
+ // Skip the echo of our own URL write, or it sends a second request
+ if (!objectsEqual(nextFilters, values.cohortFilters)) {
+ actions.setCohortFilters(nextFilters, true, false)
+ }
let currentSorting = values.cohortSorting
@@ -391,7 +403,10 @@ export const cohortsSceneLogic = kea<cohortsSceneLogicType>([
actions.setCohortSorting(currentSorting)
},
})),
- afterMount(({ actions }) => {
- actions.loadCohorts()
+ afterMount(({ actions, values }) => {
+ // urlToAction runs first and already loads when the URL carries filters
+ if (!values.cohortsLoading) {
+ actions.loadCohorts()
+ }
}),
])
diff --git a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
index 22d65c938c1c..964b6ff0f7ec 100644
--- a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
+++ b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
@@ -142,6 +142,57 @@ describe('eventDefinitionsTableLogic', () => {
logic.mount()
})
+ describe('request timing', () => {
+ const listRequests = (): unknown[][] =>
+ api.get.mock.calls.filter(([url]) => String(url).includes('/event_definitions'))
+
+ beforeEach(() => {
+ logic.unmount()
+ jest.useFakeTimers()
+ api.get.mockClear()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each<[string, Record<string, string>]>([
+ ['a bare URL', {}],
+ ['a search in the URL', { event: 'checkout' }],
+ ])('sends one request at once when the page opens on %s', async (_, searchParams) => {
+ router.actions.push(urls.eventDefinitions(), searchParams)
+ logic = eventDefinitionsTableLogic({ key: '1', syncWithUrl: true })
+ logic.mount()
+
+ expect(listRequests()).toHaveLength(1)
+
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(listRequests()).toHaveLength(1)
+ })
+
+ it.each([
+ ['the list has results', false],
+ ['the list is empty', true],
+ ])('waits for typing in the search box to pause, then sends one request when %s', async (_, emptyList) => {
+ router.actions.push(urls.eventDefinitions())
+ logic = eventDefinitionsTableLogic({ key: '1', syncWithUrl: true })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(1000)
+ if (emptyList) {
+ logic.actions.loadEventDefinitionsSuccess({ count: 0, results: [] })
+ }
+ api.get.mockClear()
+
+ logic.actions.setFilters({ event: 'chec' })
+ logic.actions.setFilters({ event: 'checkout' })
+ await jest.advanceTimersByTimeAsync(200 - 1)
+ expect(listRequests()).toHaveLength(0)
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(listRequests()).toEqual([[expect.stringContaining('search=checkout')]])
+ })
+ })
+
describe('event definitions', () => {
it('load event definitions on navigate and cache', async () => {
const capture = jest.spyOn(posthog, 'capture')
@@ -287,9 +338,9 @@ describe('eventDefinitionsTableLogic', () => {
})
expect(api.get).toHaveBeenCalledTimes(3)
- expect(api.get).toHaveBeenNthCalledWith(1, propertiesStartingUrl)
- expect(api.get).toHaveBeenNthCalledWith(2, `api/projects/${MOCK_TEAM_ID}/events?event=event1&limit=1`)
- expect(api.get).toHaveBeenNthCalledWith(3, startingUrl)
+ expect(api.get).toHaveBeenNthCalledWith(1, startingUrl)
+ expect(api.get).toHaveBeenNthCalledWith(2, propertiesStartingUrl)
+ expect(api.get).toHaveBeenNthCalledWith(3, `api/projects/${MOCK_TEAM_ID}/events?event=event1&limit=1`)
await expectLogic(logic, () => {
logic.actions.loadPropertiesForEvent(eventDefinition, startingUrl)
diff --git a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
index 19650b7250f4..a58a9f0d9aa7 100644
--- a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
@@ -79,6 +79,18 @@ export function normalizePropertyDefinitionEndpointUrl(
})
}
+function filtersFromSearchParams(searchParams: Record<string, any>): Filters {
+ const { event, event_type, ordering, tags, verified } = searchParams
+ return {
+ ...DEFAULT_FILTERS,
+ ...(event !== undefined && { event }),
+ ...(event_type !== undefined && { event_type }),
+ ...(ordering !== undefined && { ordering }),
+ ...(parseTagsFilter(tags) !== undefined && { tags: parseTagsFilter(tags) }),
+ ...(verified !== undefined && { verified: verified === 'true' || verified === true }),
+ }
+}
+
function normalizeEventDefinitionEndpointUrl({
url,
searchParams = {},
@@ -289,7 +301,11 @@ export interface eventDefinitionsTableLogicActions {
setEventDefinitionPropertiesLoading: (ids: string[]) => {
ids: string[]
}
- setFilters: (filters: Partial<Filters>) => {
+ setFilters: (
+ filters: Partial<Filters>,
+ debounce?: boolean
+ ) => {
+ debounce: boolean
filters: Partial<Filters>
}
setLocalEventDefinition: (definition: EventDefinition) => {
@@ -369,7 +385,7 @@ export const eventDefinitionsTableLogic = kea<eventDefinitionsTableLogicType>([
loadEventDefinitions: (url: string | null = '') => ({ url }),
loadEventExample: (definition: EventDefinition) => ({ definition }),
loadPropertiesForEvent: (definition: EventDefinition, url: string | null = '') => ({ definition, url }),
- setFilters: (filters: Partial<Filters>) => ({ filters }),
+ setFilters: (filters: Partial<Filters>, debounce: boolean = true) => ({ filters, debounce }),
setLocalEventDefinition: (definition: EventDefinition) => ({ definition }),
applyBulkTagUpdates: (updates: { id: number | string; tags: string[] }[]) => ({ updates }),
applyBulkVerifiedUpdates: (updates: { id: string; verified: boolean }[]) => ({ updates }),
@@ -415,7 +431,6 @@ export const eventDefinitionsTableLogic = kea<eventDefinitionsTableLogicType>([
return cache.apiCache[url]
}
- await breakpoint(200)
cache.eventsStartTime = performance.now()
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
const response = await api.get(url)
@@ -657,7 +672,12 @@ export const eventDefinitionsTableLogic = kea<eventDefinitionsTableLogicType>([
],
})),
listeners(({ actions, values, cache }) => ({
- setFilters: async () => {
+ setFilters: async ({ debounce }, breakpoint) => {
+ if (debounce) {
+ cache.filtersLoadPending = true
+ await breakpoint(200)
+ }
+ cache.filtersLoadPending = false
actions.loadEventDefinitions()
},
bulkUpdateVerifiedSuccess: ({ bulkVerifiedResult, payload }) => {
@@ -720,22 +740,18 @@ export const eventDefinitionsTableLogic = kea<eventDefinitionsTableLogicType>([
}
},
})),
- urlToAction(({ actions, values }) => ({
+ urlToAction(({ actions, values, cache }) => ({
'/data-management/events': (_, searchParams) => {
- const { event, event_type, ordering, tags, verified } = searchParams
-
- const filtersFromUrl: Filters = {
- ...DEFAULT_FILTERS,
- ...(event !== undefined && { event }),
- ...(event_type !== undefined && { event_type }),
- ...(ordering !== undefined && { ordering }),
- ...(parseTagsFilter(tags) !== undefined && { tags: parseTagsFilter(tags) }),
- ...(verified !== undefined && { verified: verified === 'true' || verified === true }),
- }
+ const filtersFromUrl = filtersFromSearchParams(searchParams)
if (!objectsEqual(values.filters, filtersFromUrl)) {
- actions.setFilters(filtersFromUrl)
- } else if (!values.eventDefinitions.results.length && !values.eventDefinitionsLoading) {
+ actions.setFilters(filtersFromUrl, false)
+ } else if (
+ // A debounced filter change already writes this URL, so loading here would skip the debounce
+ !cache.filtersLoadPending &&
+ !values.eventDefinitions.results.length &&
+ !values.eventDefinitionsLoading
+ ) {
actions.loadEventDefinitions()
}
},
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
index 36627759de3b..b8d195e69aa2 100644
--- a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
@@ -72,6 +72,57 @@ describe('propertyDefinitionsTableLogic', () => {
logic.mount()
})
+ describe('request timing', () => {
+ const listRequests = (): unknown[][] =>
+ api.get.mock.calls.filter(([url]) => String(url).includes('/property_definitions'))
+
+ beforeEach(() => {
+ logic.unmount()
+ jest.useFakeTimers()
+ api.get.mockClear()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each<[string, Record<string, string>]>([
+ ['a bare URL', {}],
+ ['a search in the URL', { property: 'checkout' }],
+ ])('sends one request at once when the page opens on %s', async (_, searchParams) => {
+ router.actions.push(urls.propertyDefinitions(), searchParams)
+ logic = propertyDefinitionsTableLogic({ key: '1', syncWithUrl: true })
+ logic.mount()
+
+ expect(listRequests()).toHaveLength(1)
+
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(listRequests()).toHaveLength(1)
+ })
+
+ it.each([
+ ['the list has results', false],
+ ['the list is empty', true],
+ ])('waits for typing in the search box to pause, then sends one request when %s', async (_, emptyList) => {
+ router.actions.push(urls.propertyDefinitions())
+ logic = propertyDefinitionsTableLogic({ key: '1', syncWithUrl: true })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(1000)
+ if (emptyList) {
+ logic.actions.loadPropertyDefinitionsSuccess({ count: 0, results: [] })
+ }
+ api.get.mockClear()
+
+ logic.actions.setFilters({ property: 'chec' })
+ logic.actions.setFilters({ property: 'checkout' })
+ await jest.advanceTimersByTimeAsync(500 - 1)
+ expect(listRequests()).toHaveLength(0)
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(listRequests()).toEqual([[expect.stringContaining('search=checkout')]])
+ })
+ })
+
describe('property definitions', () => {
const startingUrl = `api/projects/${MOCK_TEAM_ID}/property_definitions${
combineUrl('', {
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
index 4adbe39a3d61..3de62431d4d2 100644
--- a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.ts
@@ -85,7 +85,11 @@ export interface propertyDefinitionsTableLogicActions {
url: string | null
}
}
- setFilters: (filters: Partial<Filters>) => {
+ setFilters: (
+ filters: Partial<Filters>,
+ debounce?: boolean
+ ) => {
+ debounce: boolean
filters: Partial<Filters>
}
setHoveredDefinition: (definitionKey: string | null) => {
@@ -126,7 +130,7 @@ export interface propertyDefinitionsTableLogicMeta {
__keaTypeGenInternalSelectorTypes: {
propertyTypeOptions: (
groupTypes: Map<GroupTypeIndex, GroupType>,
- aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun
+ aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
) => LemonSelectOption<string>[]
showVerifiedFilter: (propertyDefinitions: PropertyDefinitionsPaginatedResponse) => boolean
}
@@ -150,7 +154,7 @@ export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicTy
loadPropertyDefinitions: (url: string | null = '') => ({
url,
}),
- setFilters: (filters: Partial<Filters>) => ({ filters }),
+ setFilters: (filters: Partial<Filters>, debounce: boolean = true) => ({ filters, debounce }),
setHoveredDefinition: (definitionKey: string | null) => ({ definitionKey }),
setOpenedDefinition: (id: string | null) => ({ id }),
setLocalPropertyDefinition: (definition: PropertyDefinition) => ({ definition }),
@@ -216,7 +220,6 @@ export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicTy
url = api.propertyDefinitions.determineListEndpoint({})
}
cache.propertiesStartTime = performance.now()
- await breakpoint(200)
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
const response = await api.get(url)
breakpoint()
@@ -264,8 +267,12 @@ export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicTy
],
})),
listeners(({ actions, values, cache }) => ({
- setFilters: async (_, breakpoint) => {
- await breakpoint(500)
+ setFilters: async ({ debounce }, breakpoint) => {
+ if (debounce) {
+ cache.filtersLoadPending = true
+ await breakpoint(500)
+ }
+ cache.filtersLoadPending = false
const params: Record<string, any> = {
offset: 0,
search: values.filters.property,
@@ -303,7 +310,7 @@ export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicTy
})
},
})),
- urlToAction(({ actions, values }) => ({
+ urlToAction(({ actions, values, cache }) => ({
[urls.propertyDefinitions()]: (_, searchParams) => {
if (values.propertyDefinitionsLoading) {
return
@@ -317,8 +324,12 @@ export const propertyDefinitionsTableLogic = kea<propertyDefinitionsTableLogicTy
: undefined,
}
if (!objectsEqual(cleanFilters(values.filters), cleanFilters(parsedParams))) {
- actions.setFilters(parsedParams as Filters)
- } else if (!values.propertyDefinitions.results.length) {
+ actions.setFilters(parsedParams as Filters, false)
+ } else if (
+ // A debounced filter change already writes this URL, so loading here would skip the debounce
+ !cache.filtersLoadPending &&
+ !values.propertyDefinitions.results.length
+ ) {
actions.loadPropertyDefinitions()
}
},
diff --git a/products/conversations/frontend/components/TicketListFilters/TicketListFilters.tsx b/products/conversations/frontend/components/TicketListFilters/TicketListFilters.tsx
index 457a7a1fa644..ef4ca16e95f5 100644
--- a/products/conversations/frontend/components/TicketListFilters/TicketListFilters.tsx
+++ b/products/conversations/frontend/components/TicketListFilters/TicketListFilters.tsx
@@ -79,7 +79,7 @@ export function TicketListFilters({ embedded = false }: TicketListFiltersProps):
icon={<IconRefresh />}
loading={ticketsLoading}
disabledReason={ticketsLoading ? 'Loading tickets...' : undefined}
- onClick={loadTickets}
+ onClick={() => loadTickets()}
size="small"
data-attr="refresh-tickets"
tooltip="Refresh"
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 86bb828a041f..c79fe0a11489 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -352,8 +352,8 @@ export interface supportTicketSceneLogicActions {
setTicketContext: (context: ImpersonationTicketContext | null) => {
context: ImpersonationTicketContext | null
} // impersonationNoticeLogic
- loadTickets: () => {
- value: true
+ loadTickets: (debounce?: boolean | undefined) => {
+ debounce: boolean
} // supportTicketsSceneLogic
loadTags: () => {
value: true
diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
index a82c698fedfe..ac9a8f8951b7 100644
--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.test.ts
@@ -3,6 +3,7 @@ import { MOCK_DEFAULT_ORGANIZATION_MEMBER } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -176,6 +177,49 @@ describe('supportTicketsSceneLogic', () => {
})
})
+ describe('request timing', () => {
+ let logic: ReturnType<typeof supportTicketsSceneLogic.build>
+ let listTickets: jest.SpyInstance
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ initKeaTests()
+ listTickets = jest
+ .spyOn(api.conversationsTickets, 'list')
+ .mockResolvedValue({ results: [], count: 0 } as any)
+ router.actions.push(urls.supportTickets())
+ logic = supportTicketsSceneLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ listTickets.mockRestore()
+ jest.useRealTimers()
+ })
+
+ it('sends one ticket list request at once when the list opens', async () => {
+ expect(listTickets).toHaveBeenCalledTimes(1)
+
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(listTickets).toHaveBeenCalledTimes(1)
+ })
+
+ it('waits for typing in the search box to pause, then sends one request', async () => {
+ await jest.advanceTimersByTimeAsync(1000)
+ listTickets.mockClear()
+
+ logic.actions.setSearchQuery('refu')
+ logic.actions.setSearchQuery('refund')
+ await jest.advanceTimersByTimeAsync(299)
+ expect(listTickets).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(listTickets).toHaveBeenCalledTimes(1)
+ expect(listTickets).toHaveBeenCalledWith(expect.objectContaining({ search: 'refund' }))
+ })
+ })
+
describe('assignee filter param', () => {
let logic: ReturnType<typeof supportTicketsSceneLogic.build>
let lastAssigneeParam: string | null = null
diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
index 8a8a5340d824..8d89834b9f82 100644
--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts
@@ -269,8 +269,8 @@ export interface supportTicketsSceneLogicActions {
loadSavedView: (shortId: string) => {
shortId: string
}
- loadTickets: () => {
- value: true
+ loadTickets: (debounce?: boolean) => {
+ debounce: boolean
}
resetFilters: () => {
value: true
@@ -414,7 +414,7 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
setSorting: (sorting: Sorting | null) => ({ sorting }),
setSearchQuery: (query: string) => ({ query }),
setCurrentPage: (page: number) => ({ page }),
- loadTickets: true,
+ loadTickets: (debounce: boolean = true) => ({ debounce }),
setTickets: (tickets: Ticket[]) => ({ tickets }),
setTotalCount: (count: number) => ({ count }),
setTicketsLoading: (loading: boolean) => ({ loading }),
@@ -726,8 +726,10 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
],
}),
listeners(({ actions, values, props, cache }) => ({
- loadTickets: async (_, breakpoint) => {
- await breakpoint(300)
+ loadTickets: async ({ debounce }, breakpoint) => {
+ if (debounce) {
+ await breakpoint(300)
+ }
const params: Record<string, any> = {}
if (props.distinctIds && props.distinctIds.length > 0) {
@@ -1074,6 +1076,6 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([
}
}
}
- actions.loadTickets()
+ actions.loadTickets(false)
}),
])