Skip to content

Commit

Permalink
fix(condo): DOMA-11011 remove unnecessary queries (#5730)
Browse files Browse the repository at this point in the history
* fix(condo): DOMA-11007 save console.log

* fix(condo): DOMA-11007 proof of work

* fix(condo): DOMA-11007 delete console.log

* fix(condo): DOMA-11007 comeback useEffect in organization

* fix(condo): DOMA-11011 removed request to getAllMiniApps

* fix(condo): DOMA-11011 rewrite useLazyQuery on useQuery

* fix(condo): DOMA-11011 add user to all data in organization

* fix(condo): DOMA-11011 add wrap for refetch

* fix(condo): DOMA-11011 fix eslint
  • Loading branch information
tolmachev21 authored Jan 29, 2025
1 parent e5f1617 commit a1dfb2f
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ export const B2BAppPage: React.FC<B2BPageProps> = ({ id }) => {
setModalOpen(true)
})
const createContextAction = useCallback(() => {
initialAction({ organization: { connect: { id: organizationId } }, app: { connect: { id: appId } } })
if (!userOrganization.isLoading) {
initialAction({ organization: { connect: { id: organizationId } }, app: { connect: { id: appId } } })
}
}, [initialAction, organizationId, appId])

const handleCloseModal = useCallback(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { SortAllMiniAppsBy } from '@app/condo/schema'
import get from 'lodash/get'
import React, { createContext, useCallback, useContext, useEffect, useState } from 'react'
import React, { createContext, useCallback, useContext, useState } from 'react'

import { useLazyQuery } from '@open-condo/next/apollo'
import { useQuery } from '@open-condo/next/apollo'
import { useAuth } from '@open-condo/next/auth'
import { useOrganization } from '@open-condo/next/organization'

import { ALL_MENU_CATEGORIES, DEFAULT_MENU_CATEGORY } from '@condo/domains/common/constants/menuCategories'
Expand All @@ -28,12 +29,27 @@ export const ConnectedWithIconsContext = createContext<IConnectedAppsWithIconsCo
})

export const ConnectedAppsWithIconsContextProvider: React.FC = ({ children }) => {
const { isAuthenticated, isLoading: isUserLoading } = useAuth()
const { organization } = useOrganization()
const orgId = get(organization, 'id', null)
const [appsByCategories, setAppsByCategories] = useState<AppsByCategories>({})
const [connectedApps, setConnectedApps] = useState<Array<string>>([])

const [fetchMiniAppsQuery] = useLazyQuery(ALL_MINI_APPS_QUERY, {
const { refetch } = useQuery(ALL_MINI_APPS_QUERY, {
variables: {
data: {
dv: 1,
sender: getClientSideSenderInfo(),
organization: { id: orgId },
where: {
connected: true,
accessible: true,
app: { icon_not: null },
},
sortBy: SortAllMiniAppsBy.ConnectedAtAsc,
},
},
skip: isUserLoading || !isAuthenticated || !orgId,
onCompleted: (data) => {
const apps = get(data, 'objs', [])
const appsByCategories: AppsByCategories = Object.assign({}, ...ALL_MENU_CATEGORIES.map(category =>({ [category]: [] })))
Expand All @@ -50,35 +66,12 @@ export const ConnectedAppsWithIconsContextProvider: React.FC = ({ children }) =>
},
})

const fetchMiniApps = useCallback(() => {
if (orgId) {
fetchMiniAppsQuery({
variables: {
data: {
dv: 1,
sender: getClientSideSenderInfo(),
organization: { id: orgId },
where: {
connected: true,
accessible: true,
app: { icon_not: null },
},
sortBy: SortAllMiniAppsBy.ConnectedAtAsc,
},
},
})
} else {
setConnectedApps([])
setAppsByCategories(Object.assign({}, ...ALL_MENU_CATEGORIES.map(category =>({ [category]: [] }))))
}
}, [orgId, fetchMiniAppsQuery])

useEffect(() => {
fetchMiniApps()
}, [orgId, fetchMiniApps])
const refetchAuth = useCallback(async () => {
await refetch()
}, [refetch])

return (
<ConnectedWithIconsContext.Provider value={{ appsByCategories: appsByCategories, refetch: fetchMiniApps, connectedAppsIds: connectedApps }}>
<ConnectedWithIconsContext.Provider value={{ appsByCategories: appsByCategories, refetch: refetchAuth, connectedAppsIds: connectedApps }}>
{children}
</ConnectedWithIconsContext.Provider>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const GlobalAppsContainer: React.FC = () => {
// (Provider addOrigin must be changed to addFrame or something like that)
// 2. Move constants like REQUEST_FEATURE_MESSAGE_NAME, ORGANIZATION_CHANGE_MESSAGE_NAME to incoming bridge events
// so miniapps can use bridge.subscribe with Type safety on them!
const { user } = useAuth()
const { user, isLoading } = useAuth()
const { organization } = useOrganization()
const organizationId = get(organization, 'id', null)

Expand All @@ -37,7 +37,7 @@ export const GlobalAppsContainer: React.FC = () => {
isHidden: false,
},
sortBy: [SortB2BAppsBy.CreatedAtAsc],
}, { skip: !user || !organizationId })
}, { skip: !user || !organizationId || isLoading })

const appUrls = objs.map(app => app.appUrl)

Expand Down
7 changes: 4 additions & 3 deletions apps/condo/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ const MenuItems: React.FC = () => {
const isSPPOrg = useFlag(SERVICE_PROVIDER_PROFILE)
const isMarketplaceEnabled = useFlag(MARKETPLACE)

const { isAuthenticated, isLoading } = useAuth()
const { link, organization } = useOrganization()
const { isExpired } = useServiceSubscriptionContext()
const hasSubscriptionFeature = hasFeature('subscription')
Expand All @@ -159,7 +160,7 @@ const MenuItems: React.FC = () => {
const orgId = get(organization, 'id', null)
const orgFeatures = get(organization, 'features', [])
const sppBillingId = get(sppConfig, 'BillingIntegrationId', null)
const { obj: billingCtx } = BillingContext.useObject({ where: { integration: { id: sppBillingId }, organization: { id: orgId } } })
const { obj: billingCtx } = BillingContext.useObject({ where: { integration: { id: sppBillingId }, organization: { id: orgId } } }, { skip: !isAuthenticated || isLoading })
const anyReceiptsLoaded = Boolean(get(billingCtx, 'lastReport', null))
const hasAccessToBilling = get(role, 'canReadPayments', false) || get(role, 'canReadBillingReceipts', false)
const isManagingCompany = get(organization, 'type', MANAGING_COMPANY_TYPE) === MANAGING_COMPANY_TYPE
Expand Down Expand Up @@ -388,7 +389,7 @@ const MenuItems: React.FC = () => {
}

const TasksProvider = ({ children }) => {
const { user } = useAuth()
const { user, isLoading } = useAuth()
// Use UI interfaces for all tasks, that are supposed to be tracked
const { TicketDocumentGenerationTask: TicketDocumentGenerationTaskUIInterface } = useTicketDocumentGenerationTaskUIInterface()
const { TicketExportTask: TicketExportTaskUIInterface } = useTicketExportTaskUIInterface()
Expand All @@ -405,7 +406,7 @@ const TasksProvider = ({ children }) => {
// Load all tasks with 'processing' status
const { data, loading: isProcessingTasksLoading } = useGetProcessingTasksQuery({
variables: { userId: user?.id || null, createdAtGte: dayjs().startOf('day').toISOString() },
skip: !user?.id,
skip: !user?.id || isLoading,
})

const { records: miniAppTasks, loading: isMiniAppTasksLoading } = MiniAppTaskUIInterface.storage.useTasks(
Expand Down
5 changes: 4 additions & 1 deletion packages/next/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,9 @@ const _withAuthLegacy: WithAuthLegacyType = ({ ssr = false, ...opts } = {}) => P
const AuthProvider: React.FC = ({ children }) => {
const apolloClient = useApolloClient()

const { data, loading: userLoading, refetch } = useQuery(USER_QUERY)
const { data, loading: userLoading, refetch } = useQuery(USER_QUERY, {
notifyOnNetworkStatusChange: true,
})

const user = useMemo(() => get(data, 'authenticatedUser') || null, [data])

Expand All @@ -287,6 +289,7 @@ const AuthProvider: React.FC = ({ children }) => {
})

const [signOutMutation, { loading: signOutLoading }] = useMutation(SIGNOUT_MUTATION, {
refetchQueries: [USER_QUERY],
onCompleted: async () => {
removeCookieEmployeeId()
await apolloClient.cache.reset()
Expand Down
26 changes: 13 additions & 13 deletions packages/next/organization.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ const OrganizationProvider: React.FC<OrganizationProviderProps> = ({
children,
useInitialEmployeeId,
}) => {
const auth = useAuth()
const { user, isLoading: userLoading } = useAuth()
const { employeeId } = useInitialEmployeeId()
const [activeEmployeeId, setActiveEmployeeId] = useState<string | null>(employeeId)

Expand All @@ -335,14 +335,14 @@ const OrganizationProvider: React.FC<OrganizationProviderProps> = ({

const { loading: employeeLoading, refetch, data } = useQuery(GET_ORGANIZATION_EMPLOYEE_QUERY, {
variables: {
userId: auth?.user?.id || null,
userId: user?.id || null,
employeeId: activeEmployeeId,
},
skip: auth.isLoading || !auth.user || !auth.user.id || !activeEmployeeId,
skip: userLoading || !user || !user.id || !activeEmployeeId,
onError,
})

const isLoading = auth.isLoading || employeeLoading
const isLoading = userLoading || employeeLoading

const [activeEmployee, setActiveEmployee] = useState(get(data, ['employees', 0]) || null)

Expand Down Expand Up @@ -384,25 +384,25 @@ const OrganizationProvider: React.FC<OrganizationProviderProps> = ({
}, [data, activeEmployee])

useEffect(() => {
if (auth.isLoading) return
if (!auth.user && activeEmployee !== null) {
if (userLoading) return
if (!user && activeEmployee !== null) {
setActiveEmployee(null)
setActiveEmployeeId(null)
}
}, [auth.user])
}, [user])

if (DEBUG_RERENDERS) console.log('OrganizationProvider()', activeEmployee, 'loading', employeeLoading, 'skip', (auth.isLoading || !auth.user || !activeEmployeeId))
if (DEBUG_RERENDERS) console.log('OrganizationProvider()', activeEmployee, 'loading', employeeLoading, 'skip', (userLoading || !user || !activeEmployeeId))

return (
<OrganizationContext.Provider
value={{
selectLink: handleSelectLink,
selectEmployee: handleSelectEmployee,
isLoading: (!auth.user || !activeEmployeeId) ? false : isLoading,
link: (activeEmployee && activeEmployee.id) ? activeEmployee : null,
organization: (activeEmployee && activeEmployee.organization) ? activeEmployee.organization : null,
employee: (activeEmployee && activeEmployee.id) ? activeEmployee : null,
role: (activeEmployee && activeEmployee.role) ? activeEmployee.role : null,
isLoading: (!user || !activeEmployeeId) ? false : isLoading,
link: (user && activeEmployee && activeEmployee.id) ? activeEmployee : null,
organization: (user && activeEmployee && activeEmployee.organization) ? activeEmployee.organization : null,
employee: (user && activeEmployee && activeEmployee.id) ? activeEmployee : null,
role: (user && activeEmployee && activeEmployee.role) ? activeEmployee.role : null,
}}
children={children}
/>
Expand Down

0 comments on commit a1dfb2f

Please sign in to comment.