Skip to content

Commit

Permalink
fix: Reduce the number of requests made on load (#18486)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjackwhite authored Nov 10, 2023
1 parent 1d2b727 commit 00a0dac
Show file tree
Hide file tree
Showing 14 changed files with 62 additions and 63 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions frontend/src/lib/utils/kea-logic-builders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BuiltLogic, afterMount } from 'kea'
/**
* Some kea logics are used heavily across multiple areas so we keep it mounted once loaded with this trick.
*/
export function permanentlyMount(): (logic: BuiltLogic) => void {
return (logic) => {
afterMount(() => {
if (!logic.cache._permanentMount) {
logic.cache._permanentMount = true
logic.wrapper.mount()
}
})(logic)
}
}
2 changes: 2 additions & 0 deletions frontend/src/models/actionsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import api from 'lib/api'
import { ActionType } from '~/types'
import type { actionsModelType } from './actionsModelType'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

export interface ActionsModelProps {
params?: string
Expand Down Expand Up @@ -57,4 +58,5 @@ export const actionsModel = kea<actionsModelType>([
}
},
})),
permanentlyMount(),
])
2 changes: 2 additions & 0 deletions frontend/src/models/annotationsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { RawAnnotationType, AnnotationType } from '~/types'
import { loaders } from 'kea-loaders'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
import { dayjsUtcToTimezone } from 'lib/dayjs'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

export type AnnotationData = Pick<RawAnnotationType, 'date_marker' | 'scope' | 'content' | 'dashboard_item'>
export type AnnotationDataWithoutInsight = Omit<AnnotationData, 'dashboard_item'>
Expand Down Expand Up @@ -125,4 +126,5 @@ export const annotationsModel = kea<annotationsModelType>([
actions.loadAnnotations()
}
}),
permanentlyMount(),
])
40 changes: 27 additions & 13 deletions frontend/src/models/cohortsModel.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { loaders } from 'kea-loaders'
import { kea, path, connect, actions, reducers, selectors, listeners, events } from 'kea'
import { kea, path, connect, actions, reducers, selectors, listeners, beforeUnmount, afterMount } from 'kea'
import api from 'lib/api'
import type { cohortsModelType } from './cohortsModelType'
import { CohortType, ExporterFormat } from '~/types'
import { personsLogic } from 'scenes/persons/personsLogic'
import { deleteWithUndo, processCohort } from 'lib/utils'
import { triggerExport } from 'lib/components/ExportButton/exporter'
import { isAuthenticatedTeam, teamLogic } from 'scenes/teamLogic'
import Fuse from 'fuse.js'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

const POLL_TIMEOUT = 5000

Expand Down Expand Up @@ -47,7 +49,7 @@ export const cohortsModel = kea<cohortsModelType>([
}
return [...state].map((existingCohort) => (existingCohort.id === cohort.id ? cohort : existingCohort))
},
cohortCreated: (state = [], { cohort }) => {
cohortCreated: (state, { cohort }) => {
if (!cohort) {
return state
}
Expand All @@ -68,6 +70,18 @@ export const cohortsModel = kea<cohortsModelType>([
(cohorts): Partial<Record<string | number, CohortType>> =>
Object.fromEntries(cohorts.map((cohort) => [cohort.id, cohort])),
],

cohortsSearch: [
(s) => [s.cohorts],
(cohorts): ((term: string) => CohortType[]) => {
const fuse = new Fuse<CohortType>(cohorts ?? [], {
keys: ['name'],
threshold: 0.3,
})

return (term) => fuse.search(term).map((result) => result.item)
},
],
}),
listeners(({ actions }) => ({
loadCohortsSuccess: async ({ cohorts }: { cohorts: CohortType[] }) => {
Expand Down Expand Up @@ -97,15 +111,15 @@ export const cohortsModel = kea<cohortsModelType>([
})
},
})),
events(({ actions, values }) => ({
afterMount: () => {
if (isAuthenticatedTeam(values.currentTeam)) {
// Don't load on shared insights/dashboards
actions.loadCohorts()
}
},
beforeUnmount: () => {
clearTimeout(values.pollTimeout || undefined)
},
})),
beforeUnmount(({ values }) => {
clearTimeout(values.pollTimeout || undefined)
}),

afterMount(({ actions, values }) => {
if (isAuthenticatedTeam(values.currentTeam)) {
// Don't load on shared insights/dashboards
actions.loadCohorts()
}
}),
permanentlyMount(),
])
12 changes: 6 additions & 6 deletions frontend/src/models/dashboardsModel.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { loaders } from 'kea-loaders'
import { kea, path, connect, actions, reducers, selectors, listeners, events } from 'kea'
import { kea, path, connect, actions, reducers, selectors, listeners, afterMount } from 'kea'
import { router, urlToAction } from 'kea-router'
import api, { PaginatedResponse } from 'lib/api'
import { idToKey, isUserLoggedIn } from 'lib/utils'
Expand All @@ -11,6 +11,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { lemonToast } from 'lib/lemon-ui/lemonToast'
import { tagsModel } from '~/models/tagsModel'
import { GENERATED_DASHBOARD_PREFIX } from 'lib/constants'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

export const dashboardsModel = kea<dashboardsModelType>([
path(['models', 'dashboardsModel']),
Expand Down Expand Up @@ -321,11 +322,10 @@ export const dashboardsModel = kea<dashboardsModelType>([
}
},
})),
events(({ actions }) => ({
afterMount: () => {
actions.loadDashboards()
},
})),
afterMount(({ actions }) => {
actions.loadDashboards()
}),
permanentlyMount(),
])

export function nameCompareFunction(a: DashboardBasicType, b: DashboardBasicType): number {
Expand Down
14 changes: 0 additions & 14 deletions frontend/src/models/index.ts

This file was deleted.

2 changes: 2 additions & 0 deletions frontend/src/models/propertyDefinitionsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'
import { colonDelimitedDuration } from 'lib/utils'
import { captureTimeToSeeData } from 'lib/internalMetrics'
import { teamLogic } from 'scenes/teamLogic'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

export type PropertyDefinitionStorage = Record<string, PropertyDefinition | PropertyDefinitionState>

Expand Down Expand Up @@ -367,4 +368,5 @@ export const propertyDefinitionsModel = kea<propertyDefinitionsModelType>([
},
],
}),
permanentlyMount(),
])
10 changes: 0 additions & 10 deletions frontend/src/scenes/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { userLogic } from 'scenes/userLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { appLogicType } from './AppType'
import { models } from '~/models'
import { teamLogic } from './teamLogic'
import { LoadedScene } from 'scenes/sceneTypes'
import { appScenes } from 'scenes/appScenes'
Expand Down Expand Up @@ -67,8 +66,6 @@ export const appLogic = kea<appLogicType>([

export function App(): JSX.Element | null {
const { showApp, showingDelayedSpinner } = useValues(appLogic)
const { user } = useValues(userLogic)
const { currentTeamId } = useValues(teamLogic)
const { featureFlags } = useValues(featureFlagLogic)
useMountedLogic(sceneLogic({ scenes: appScenes }))

Expand All @@ -83,7 +80,6 @@ export function App(): JSX.Element | null {
if (showApp) {
return (
<>
{user && currentTeamId ? <Models /> : null}
<LoadedSceneLogics />
<AppScene />
</>
Expand Down Expand Up @@ -114,12 +110,6 @@ function LoadedSceneLogics(): JSX.Element {
)
}

/** Loads every logic in the "src/models" folder */
function Models(): null {
useMountedLogic(models)
return null
}

function AppScene(): JSX.Element | null {
useMountedLogic(breadcrumbsLogic)
const { user } = useValues(userLogic)
Expand Down
18 changes: 4 additions & 14 deletions frontend/src/scenes/cohorts/Cohorts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { cohortsModel } from '../../models/cohortsModel'
import { useValues, useActions } from 'kea'
import { AvailableFeature, CohortType, ProductKey } from '~/types'
import './Cohorts.scss'
import Fuse from 'fuse.js'
import { createdAtColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { Link } from 'lib/lemon-ui/Link'
import { dayjs } from 'lib/dayjs'
Expand All @@ -21,24 +20,15 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { ListHog } from 'lib/components/hedgehogs'

const searchCohorts = (sources: CohortType[], search: string): CohortType[] => {
return new Fuse(sources, {
keys: ['name'],
threshold: 0.3,
})
.search(search)
.map((result) => result.item)
}

export function Cohorts(): JSX.Element {
const { cohorts, cohortsLoading } = useValues(cohortsModel)
const { cohorts, cohortsSearch, cohortsLoading } = useValues(cohortsModel)
const { deleteCohort, exportCohortPersons } = useActions(cohortsModel)
const { hasAvailableFeature } = useValues(userLogic)
const { searchParams } = useValues(router)
const [searchTerm, setSearchTerm] = useState<string>('')
const { user } = useValues(userLogic)
const { featureFlags } = useValues(featureFlagLogic)
const shouldShowEmptyState = cohorts.length == 0 && !cohortsLoading
const shouldShowEmptyState = cohorts?.length == 0 && !cohortsLoading
const shouldShowProductIntroduction =
!user?.has_seen_product_intro_for?.[ProductKey.COHORTS] &&
!!featureFlags[FEATURE_FLAGS.SHOW_PRODUCT_INTRO_EXISTING_PRODUCTS]
Expand Down Expand Up @@ -164,7 +154,7 @@ export function Cohorts(): JSX.Element {
productKey={ProductKey.COHORTS}
thingName="cohort"
description="Use cohorts to group people together, such as users who used your app in the last week, or people who viewed the signup page but didn’t convert."
isEmpty={cohorts.length == 0}
isEmpty={cohorts?.length == 0}
docsURL="https://posthog.com/docs/data/cohorts"
action={() => router.actions.push(urls.cohort('new'))}
customHog={ListHog}
Expand All @@ -185,7 +175,7 @@ export function Cohorts(): JSX.Element {
loading={cohortsLoading}
rowKey="id"
pagination={{ pageSize: 100 }}
dataSource={searchTerm ? searchCohorts(cohorts, searchTerm) : cohorts}
dataSource={searchTerm ? cohortsSearch(searchTerm) : cohorts ?? []}
nouns={['cohort', 'cohorts']}
data-attr="cohorts-table"
/>
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useCallback, Dispatch, SetStateAction } from 'react'
import { useState, useCallback, Dispatch, SetStateAction, useEffect } from 'react'
import { useActions, useValues } from 'kea'
import { personalAPIKeysLogic } from './personalAPIKeysLogic'
import { PersonalAPIKeyType } from '~/types'
Expand Down Expand Up @@ -70,7 +70,9 @@ function CreateKeyModal({

function PersonalAPIKeysTable(): JSX.Element {
const { keys } = useValues(personalAPIKeysLogic) as { keys: PersonalAPIKeyType[] }
const { deleteKey } = useActions(personalAPIKeysLogic)
const { deleteKey, loadKeys } = useActions(personalAPIKeysLogic)

useEffect(() => loadKeys(), [])

return (
<LemonTable
Expand Down
5 changes: 1 addition & 4 deletions frontend/src/scenes/settings/user/personalAPIKeysLogic.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { loaders } from 'kea-loaders'
import { kea, path, listeners, events } from 'kea'
import { kea, path, listeners } from 'kea'
import api from 'lib/api'
import { PersonalAPIKeyType } from '~/types'
import type { personalAPIKeysLogicType } from './personalAPIKeysLogicType'
Expand Down Expand Up @@ -37,7 +37,4 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([
lemonToast.success(`Personal API key deleted`)
},
})),
events(({ actions }) => ({
afterMount: [actions.loadKeys],
})),
])

0 comments on commit 00a0dac

Please sign in to comment.