Skip to content
Open
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
16 changes: 16 additions & 0 deletions workspaces/orchestrator/.changeset/disable-next-during-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@red-hat-developer-hub/backstage-plugin-orchestrator-form-react': minor
'@red-hat-developer-hub/backstage-plugin-orchestrator-form-api': minor
'@red-hat-developer-hub/backstage-plugin-orchestrator-form-widgets': minor
---

Disable Next button when active widgets are fetching and processing data

- Add isFetching state tracking to StepperContext using a counter to monitor multiple concurrent async operations
- Update OrchestratorFormToolbar to disable Next button when isFetching is true (in addition to existing isValidating check)
- Add handleFetchStarted and handleFetchEnded callbacks to OrchestratorFormContextProps to allow widgets to report their loading status
- Update useFetchAndEvaluate to track complete loading state (fetch + template evaluation) and notify context
- Create useProcessingState custom hook to reduce code duplication across widgets, providing a reusable pattern for tracking both fetch and processing states
- Refactor SchemaUpdater, ActiveTextInput, ActiveDropdown, and ActiveMultiSelect to use useProcessingState hook
- Track the complete loading lifecycle: fetch → process → ready, ensuring Next button is disabled until all async work completes
- Prevents race conditions where Next button becomes enabled before widgets finish processing data
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export type OrchestratorFormContextProps = {
setAuthTokenDescriptors: (authTokenDescriptors: AuthTokenDescriptor[]) => void;
getIsChangedByUser: (id: string) => boolean;
setIsChangedByUser: (id: string, isChangedByUser: boolean) => void;
handleFetchStarted?: () => void;
handleFetchEnded?: () => void;
};

// @public
Expand All @@ -58,7 +60,7 @@ export const useOrchestratorFormApiOrDefault: () => OrchestratorFormApi;

// Warnings were encountered during analysis:
//
// src/api.d.ts:98:22 - (ae-undocumented) Missing documentation for "useOrchestratorFormApiOrDefault".
// src/api.d.ts:100:22 - (ae-undocumented) Missing documentation for "useOrchestratorFormApiOrDefault".

// (No @packageDocumentation comment for this package)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export type OrchestratorFormContextProps = {
) => void;
getIsChangedByUser: (id: string) => boolean;
setIsChangedByUser: (id: string, isChangedByUser: boolean) => void;
handleFetchStarted?: () => void;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a need to have those as optional?

handleFetchEnded?: () => void;
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ const OrchestratorFormStepper = ({

export const OrchestratorFormToolbar = () => {
const { t } = useTranslation();
const { activeStep, handleBack, isValidating } = useStepperContext();
const { activeStep, handleBack, isValidating, isFetching } =
useStepperContext();
const { classes } = useStyles();

return (
Expand All @@ -109,7 +110,9 @@ export const OrchestratorFormToolbar = () => {
>
{t('common.back')}
</Button>
<SubmitButton submitting={isValidating}>{t('common.next')}</SubmitButton>
<SubmitButton submitting={isValidating || isFetching}>
{t('common.next')}
</SubmitButton>
</div>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,23 @@ const FormComponent = (decoratorProps: FormDecoratorProps) => {

const OrchestratorFormWrapper = (props: OrchestratorFormContextProps) => {
const formApi = useOrchestratorFormApiOrDefault();
const { handleFetchStarted, handleFetchEnded } = useStepperContext();

const NewComponent = useMemo(() => {
const formDecorator = formApi.getFormDecorator();
return formDecorator(FormComponent);
}, [formApi]);

return <NewComponent {...props} />;
const propsWithFetchHandlers = useMemo(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be left to the FormComponent? Similar to the handleValidate* hooks.

() => ({
...props,
handleFetchStarted,
handleFetchEnded,
}),
[props, handleFetchStarted, handleFetchEnded],
);

return <NewComponent {...propsWithFetchHandlers} />;
};

export default OrchestratorFormWrapper;
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export type StepperContext = {
isValidating: boolean;
handleValidateStarted: () => void;
handleValidateEnded: () => void;
isFetching: boolean;
handleFetchStarted: () => void;
handleFetchEnded: () => void;
t: TranslationFunction;
};

Expand All @@ -50,6 +53,8 @@ export const StepperContextProvider = ({
}) => {
const [activeStep, setActiveStep] = useState<number>(0);
const [isValidating, setIsValidating] = useState<boolean>(false);
const [fetchingCount, setFetchingCount] = useState<number>(0);

const contextData = useMemo(() => {
return {
activeStep,
Expand All @@ -61,8 +66,20 @@ export const StepperContextProvider = ({
isValidating,
handleValidateStarted: () => setIsValidating(true),
handleValidateEnded: () => setIsValidating(false),
isFetching: fetchingCount > 0,
handleFetchStarted: () => setFetchingCount(count => count + 1),
handleFetchEnded: () => setFetchingCount(count => Math.max(0, count - 1)),
t,
};
}, [t, setActiveStep, activeStep, reviewStep, isValidating, setIsValidating]);
}, [
t,
setActiveStep,
activeStep,
reviewStep,
isValidating,
setIsValidating,
fetchingCount,
setFetchingCount,
]);
return <context.Provider value={contextData}>{children}</context.Provider>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export * from './useGetExtraErrors';
export * from './useFetch';
export * from './useFetchAndEvaluate';
export * from './applySelector';
export * from './useProcessingState';
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import { JsonObject } from '@backstage/types/index';
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { UiProps } from '../uiPropTypes';
import { getErrorMessage } from './errorUtils';
import { evaluateTemplateString } from './evaluateTemplate';
Expand All @@ -30,6 +30,8 @@ export const useFetchAndEvaluate = (
formData: JsonObject,
uiProps: UiProps,
fieldId: string,
handleFetchStarted?: () => void,
handleFetchEnded?: () => void,
) => {
const unitEvaluator = useTemplateUnitEvaluator();
const retrigger = useRetriggerEvaluate(
Expand Down Expand Up @@ -88,9 +90,24 @@ export const useFetchAndEvaluate = (
template,
],
);

// Track the complete loading state (fetch + evaluation) in the parent context
const completeLoading = loading || fetchLoading;
useEffect(() => {
if (completeLoading && handleFetchStarted) {
handleFetchStarted();
return () => {
if (handleFetchEnded) {
handleFetchEnded();
}
};
}
return undefined;
}, [completeLoading, handleFetchStarted, handleFetchEnded]);

return {
text: resultText,
loading: loading || fetchLoading,
loading: completeLoading,
error: error ?? fetchError,
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { useCallback, useEffect, useState } from 'react';

/**
* Custom hook to manage processing state and notify parent context about loading status.
* This hook tracks both fetch loading and post-fetch processing, ensuring that the
* parent form knows when async operations are complete.
*
* @param fetchLoading - Whether data is currently being fetched
* @param handleFetchStarted - Optional callback to notify when processing starts
* @param handleFetchEnded - Optional callback to notify when processing ends
* @returns Object containing processing state management
*/
export const useProcessingState = (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure we need this additional hook. All the data is in the form context, including isFecthing

fetchLoading: boolean,
handleFetchStarted?: () => void,
handleFetchEnded?: () => void,
) => {
const [isProcessing, setIsProcessing] = useState(false);

// Complete loading = fetch loading OR post-fetch processing
const completeLoading = fetchLoading || isProcessing;

// Notify parent context about the complete loading state
useEffect(() => {
if (completeLoading && handleFetchStarted) {
handleFetchStarted();
return () => {
if (handleFetchEnded) {
handleFetchEnded();
}
};
}
return undefined;
}, [completeLoading, handleFetchStarted, handleFetchEnded]);

// Helper to wrap async processing with setIsProcessing
const wrapProcessing = useCallback(
async <T>(fn: () => Promise<T>): Promise<T> => {
setIsProcessing(true);
try {
return await fn();
} finally {
setIsProcessing(false);
}
},
[],
);

return {
isProcessing,
setIsProcessing,
completeLoading,
wrapProcessing,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
useRetriggerEvaluate,
useTemplateUnitEvaluator,
applySelectorArray,
useProcessingState,
} from '../utils';
import { UiProps } from '../uiPropTypes';
import { ErrorText } from './ErrorText';
Expand Down Expand Up @@ -82,6 +83,9 @@ export const ActiveDropdown: Widget<
const [labels, setLabels] = useState<string[]>();
const [values, setValues] = useState<string[]>();

const handleFetchStarted = formContext?.handleFetchStarted;
const handleFetchEnded = formContext?.handleFetchEnded;

const retrigger = useRetriggerEvaluate(
templateUnitEvaluator,
formData,
Expand All @@ -91,28 +95,37 @@ export const ActiveDropdown: Widget<

const { data, error, loading } = useFetch(formData ?? {}, uiProps, retrigger);

// Track the complete loading state (fetch + processing)
const { completeLoading, wrapProcessing } = useProcessingState(
loading,
handleFetchStarted,
handleFetchEnded,
);

useEffect(() => {
if (!data || !labelSelector || !valueSelector) {
return;
}

const doItAsync = async () => {
const selectedLabels = await applySelectorArray(data, labelSelector);
const selectedValues = await applySelectorArray(data, valueSelector);

if (selectedLabels.length !== selectedValues.length) {
setLocalError(
`Selected labels and values have different count (${selectedLabels.length} and ${selectedValues.length}) for ${props.id}`,
);
return;
}

setLabels(selectedLabels);
setValues(selectedValues);
await wrapProcessing(async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is that? Isn't tracking of the fetch enough?
These applySelector* are just sort of filtering the already loaded data

const selectedLabels = await applySelectorArray(data, labelSelector);
const selectedValues = await applySelectorArray(data, valueSelector);

if (selectedLabels.length !== selectedValues.length) {
setLocalError(
`Selected labels and values have different count (${selectedLabels.length} and ${selectedValues.length}) for ${props.id}`,
);
return;
}

setLabels(selectedLabels);
setValues(selectedValues);
});
};

doItAsync();
}, [labelSelector, valueSelector, data, props.id]);
}, [labelSelector, valueSelector, data, props.id, wrapProcessing]);

const handleChange = useCallback(
(changed: string, isByUser: boolean) => {
Expand All @@ -136,7 +149,7 @@ export const ActiveDropdown: Widget<
return <ErrorText text={localError ?? error ?? ''} id={id} />;
}

if (loading || !labels || !values) {
if (completeLoading || !labels || !values) {
return <CircularProgress size={20} />;
}

Expand Down
Loading