Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(app): Fix React Router navigation in React Query callbacks #16084

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions app/src/App/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,20 @@ export function useProtocolReceiptToast(): void {

export function useCurrentRunRoute(): string | null {
const currentRunId = useCurrentRunId({ refetchInterval: CURRENT_RUN_POLL })
const { data: runRecord } = useNotifyRunQuery(currentRunId, {
staleTime: Infinity,
enabled: currentRunId != null,
const { data: runRecord, isFetching } = useNotifyRunQuery(currentRunId, {
refetchInterval: CURRENT_RUN_POLL,
})

const runStatus = runRecord?.data.status
const runActions = runRecord?.data.actions
if (runRecord == null || runStatus == null || runActions == null) return null
if (
runRecord == null ||
runStatus == null ||
runActions == null ||
isFetching
) {
return null
}
// grabbing run id off of the run query to have all routing info come from one source of truth
const runId = runRecord.data.id
const hasRunStarted = runActions?.some(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ export function useCloseCurrentRun(): {
): void => {
if (currentRunId != null) {
dismissCurrentRun(currentRunId, {
...options,
onError: () => {
console.warn('failed to dismiss current')
},
...options,
})
}
}
Expand Down
35 changes: 21 additions & 14 deletions app/src/pages/RunSummary/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function RunSummary(): JSX.Element {
staleTime: Infinity,
onError: () => {
// in case the run is remotely deleted by a desktop app, navigate to the dash
navigate('/')
navigate('/dashboard')
},
})
const isRunCurrent = Boolean(
Expand Down Expand Up @@ -144,6 +144,19 @@ export function RunSummary(): JSX.Element {
const { reset, isResetRunLoading } = useRunControls(runId, onCloneRunSuccess)
const trackEvent = useTrackEvent()
const { closeCurrentRun, isClosingCurrentRun } = useCloseCurrentRun()
// Close the current run only if it's active and then execute the onSuccess callback. Prefer this wrapper over
// closeCurrentRun directly, since the callback is swallowed if currentRun is null.
const closeCurrentRunIfValid = (onSuccess?: () => void): void => {
if (isRunCurrent) {
closeCurrentRun({
onSuccess: () => {
onSuccess?.()
},
})
} else {
onSuccess?.()
}
}
const [showRunFailedModal, setShowRunFailedModal] = React.useState<boolean>(
false
)
Expand Down Expand Up @@ -239,11 +252,9 @@ export function RunSummary(): JSX.Element {
deleteRun(runId)
navigate('/quick-transfer')
} else {
closeCurrentRun({
onSuccess: () => {
deleteRun(runId)
navigate('/quick-transfer')
},
closeCurrentRunIfValid(() => {
deleteRun(runId)
navigate('/quick-transfer')
})
}
}
Expand Down Expand Up @@ -281,20 +292,16 @@ export function RunSummary(): JSX.Element {
robotType: FLEX_ROBOT_TYPE,
isRunCurrent,
onSkipAndHome: () => {
closeCurrentRun({
onSettled: () => {
navigate('/')
},
closeCurrentRunIfValid(() => {
navigate('/dashboard')
})
},
})
} else if (isQuickTransfer) {
returnToQuickTransfer()
} else {
closeCurrentRun({
onSettled: () => {
navigate('/')
},
closeCurrentRunIfValid(() => {
navigate('/dashboard')
})
}
}
Expand Down
22 changes: 16 additions & 6 deletions app/src/resources/runs/useNotifyAllRunsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,36 @@ import type { HostConfig, GetRunsParams, Runs } from '@opentrons/api-client'
import type { UseAllRunsQueryOptions } from '@opentrons/react-api-client/src/runs/useAllRunsQuery'
import type { QueryOptionsWithPolling } from '../useNotifyDataReady'

// TODO(jh, 08-21-24): Abstract harder.
export function useNotifyAllRunsQuery(
params: GetRunsParams = {},
options: QueryOptionsWithPolling<UseAllRunsQueryOptions, AxiosError> = {},
hostOverride?: HostConfig | null
): UseQueryResult<Runs, AxiosError> {
const { notifyOnSettled, shouldRefetch } = useNotifyDataReady({
const {
notifyOnSettled,
shouldRefetch,
isNotifyEnabled,
} = useNotifyDataReady({
topic: 'robot-server/runs',
options,
hostOverride,
})

const queryOptions = {
...options,
onSettled: isNotifyEnabled ? notifyOnSettled : options.onSettled,
refetchInterval: isNotifyEnabled ? false : options.refetchInterval,
}
const httpResponse = useAllRunsQuery(
params,
{
...(options as UseAllRunsQueryOptions),
enabled: options?.enabled !== false && shouldRefetch,
onSettled: notifyOnSettled,
},
queryOptions as UseAllRunsQueryOptions,
hostOverride
)

if (isNotifyEnabled && shouldRefetch) {
httpResponse.refetch()
}

return httpResponse
}
30 changes: 17 additions & 13 deletions app/src/resources/runs/useNotifyRunQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,32 @@ import type { Run, HostConfig } from '@opentrons/api-client'
import type { QueryOptionsWithPolling } from '../useNotifyDataReady'
import type { NotifyTopic } from '../../redux/shell/types'

// TODO(jh, 08-21-24): Abstract harder.
export function useNotifyRunQuery<TError = Error>(
runId: string | null,
options: QueryOptionsWithPolling<Run, TError> = {},
hostOverride?: HostConfig | null
): UseQueryResult<Run, TError> {
const isEnabled = options.enabled !== false && runId != null

const { notifyOnSettled, shouldRefetch } = useNotifyDataReady({
const {
notifyOnSettled,
shouldRefetch,
isNotifyEnabled,
} = useNotifyDataReady({
topic: `robot-server/runs/${runId}` as NotifyTopic,
options: { ...options, enabled: options.enabled != null && runId != null },
options,
hostOverride,
})

const httpResponse = useRunQuery(
runId,
{
...options,
enabled: isEnabled && shouldRefetch,
onSettled: notifyOnSettled,
},
hostOverride
)
const queryOptions = {
...options,
onSettled: isNotifyEnabled ? notifyOnSettled : options.onSettled,
refetchInterval: isNotifyEnabled ? false : options.refetchInterval,
}
const httpResponse = useRunQuery(runId, queryOptions, hostOverride)

if (isNotifyEnabled && shouldRefetch) {
httpResponse.refetch()
}

return httpResponse
}
23 changes: 19 additions & 4 deletions app/src/resources/useNotifyDataReady.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { UseQueryOptions } from 'react-query'
import type { HostConfig } from '@opentrons/api-client'
import type { NotifyTopic, NotifyResponseData } from '../redux/shell/types'

export type HTTPRefetchFrequency = 'once' | 'always' | null
export type HTTPRefetchFrequency = 'once' | null

export interface QueryOptionsWithPolling<TData, TError = Error>
extends UseQueryOptions<TData, TError> {
Expand All @@ -30,10 +30,20 @@ interface useNotifyDataReadyProps<TData, TError = Error> {
}

interface useNotifyDataReadyResults {
/* Reset notification refetch state. */
notifyOnSettled: () => void
/* Whether notifications indicate the server has new data ready. */
shouldRefetch: boolean
/* Whether notifications are enabled as determined by client options and notification health. */
isNotifyEnabled: boolean
}

// React query hooks perform refetches when instructed by the shell via a refetch mechanism, which useNotifyDataReady manages.
// The notification refetch states may be:
// 'once' - The shell has received an MQTT update. Execute the HTTP refetch once.
// null - The shell has not received an MQTT update. Don't execute an HTTP refetch.
//
// Eagerly assume notifications are enabled unless specified by the client via React Query options or by the shell via errors.
export function useNotifyDataReady<TData, TError = Error>({
topic,
options,
Expand All @@ -47,6 +57,7 @@ export function useNotifyDataReady<TData, TError = Error>({
const forcePollingFF = useFeatureFlag('forceHttpPolling')
const seenHostname = React.useRef<string | null>(null)
const [refetch, setRefetch] = React.useState<HTTPRefetchFrequency>(null)
const [isNotifyEnabled, setIsNotifyEnabled] = React.useState(true)

const { enabled, staleTime, forceHttpPolling } = options

Expand All @@ -69,7 +80,7 @@ export function useNotifyDataReady<TData, TError = Error>({
dispatch(notifySubscribeAction(hostname, topic))
seenHostname.current = hostname
} else {
setRefetch('always')
setIsNotifyEnabled(false)
}

return () => {
Expand All @@ -86,7 +97,7 @@ export function useNotifyDataReady<TData, TError = Error>({

const onDataEvent = React.useCallback((data: NotifyResponseData): void => {
if (data === 'ECONNFAILED' || data === 'ECONNREFUSED') {
setRefetch('always')
setIsNotifyEnabled(false)
if (data === 'ECONNREFUSED') {
doTrackEvent({
name: ANALYTICS_NOTIFICATION_PORT_BLOCK_ERROR,
Expand All @@ -104,5 +115,9 @@ export function useNotifyDataReady<TData, TError = Error>({
}
}, [refetch])

return { notifyOnSettled, shouldRefetch: refetch != null }
return {
notifyOnSettled,
shouldRefetch: refetch != null,
isNotifyEnabled,
}
}
Loading