Skip to content

Commit

Permalink
(fix): Replace global store with react context
Browse files Browse the repository at this point in the history
  • Loading branch information
NethmiRodrigo committed May 24, 2024
1 parent 970415b commit 7cc4ac3
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 105 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';
import type { FormField } from '../../types';

export type HandleConfirmDeletionProps = {
handleConfirmQuestionDeletion: (question: Readonly<FormField>) => Promise<void>;
};

export const HandleDeletionConfirmationContext = React.createContext<HandleConfirmDeletionProps | undefined>(undefined);
14 changes: 7 additions & 7 deletions src/components/repeat/repeat.component.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { FormGroup } from '@carbon/react';
import { useFormikContext } from 'formik';
import { useTranslation } from 'react-i18next';
import type { HandleConfirmDeletionFunctionStore, FormField, FormFieldProps, RenderType } from '../../types';
import type { FormField, FormFieldProps, RenderType } from '../../types';
import { evaluateAsyncExpression, evaluateExpression } from '../../utils/expression-runner';
import { isEmpty } from '../../validators/form-validator';
import styles from './repeat.scss';
Expand All @@ -11,7 +11,8 @@ import { FormContext } from '../../form-context';
import { getFieldControlWithFallback } from '../section/helpers';
import { clearSubmission } from '../../utils/common-utils';
import RepeatControls from './repeat-controls.component';
import { createErrorHandler, getGlobalStore } from '@openmrs/esm-framework';
import { createErrorHandler } from '@openmrs/esm-framework';
import { HandleDeletionConfirmationContext } from './handle-deletion-confirmation-context';

const renderingByTypeMap: Record<string, RenderType> = {
obsGroup: 'group',
Expand All @@ -27,8 +28,7 @@ const Repeat: React.FC<FormFieldProps> = ({ question, onChange, handler }) => {
const [rows, setRows] = useState([]);
const [fieldComponent, setFieldComponent] = useState(null);

const functionStore = getGlobalStore<HandleConfirmDeletionFunctionStore>('functionStore');
const { handleConfirmQuestionDeletion } = functionStore.getState();
const { handleConfirmQuestionDeletion } = useContext(HandleDeletionConfirmationContext);

useEffect(() => {
const repeatedFields = allFormFields.filter(
Expand Down Expand Up @@ -160,7 +160,7 @@ const Repeat: React.FC<FormFieldProps> = ({ question, onChange, handler }) => {
}

return (
<div>
<React.Fragment>
{isGrouped ? (
<div className={styles.container}>
<FormGroup legendText={t(question.label)} className={styles.boldLegend}>
Expand All @@ -170,7 +170,7 @@ const Repeat: React.FC<FormFieldProps> = ({ question, onChange, handler }) => {
) : (
<div>{nodes}</div>
)}
</div>
</React.Fragment>
);
};

Expand Down
176 changes: 84 additions & 92 deletions src/form-engine.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,9 @@ import { Form, Formik } from 'formik';
import { Button, ButtonSet, InlineLoading } from '@carbon/react';
import { I18nextProvider, useTranslation } from 'react-i18next';
import * as Yup from 'yup';
import { createGlobalStore, showSnackbar, useSession, type Visit } from '@openmrs/esm-framework';
import { showSnackbar, useSession, type Visit } from '@openmrs/esm-framework';
import { init, teardown } from './lifecycle';
import type {
FormField,
FormPage as FormPageProps,
FormSchema,
HandleConfirmDeletionFunctionStore,
SessionMode,
} from './types';
import type { FormField, FormPage as FormPageProps, FormSchema, SessionMode } from './types';
import { extractErrorMessagesFromResponse, reportError } from './utils/error-utils';
import { useFormJson } from './hooks/useFormJson';
import { usePostSubmissionAction } from './hooks/usePostSubmissionAction';
Expand All @@ -27,6 +21,7 @@ import Loader from './components/loaders/loader.component';
import MarkdownWrapper from './components/inputs/markdown/markdown-wrapper.component';
import PatientBanner from './components/patient-banner/patient-banner.component';
import Sidebar from './components/sidebar/sidebar.component';
import { HandleDeletionConfirmationContext } from './components/repeat/handle-deletion-confirmation-context';
import styles from './form-engine.scss';

interface FormProps {
Expand Down Expand Up @@ -76,10 +71,6 @@ export interface FormSubmissionHandler {
validate: (values) => boolean;
}

const functionStore = createGlobalStore<HandleConfirmDeletionFunctionStore | null>('functionStore', {
handleConfirmQuestionDeletion: null,
});

const FormEngine: React.FC<FormProps> = ({
formJson,
formUUID,
Expand All @@ -106,7 +97,6 @@ const FormEngine: React.FC<FormProps> = ({
isLoading: isLoadingFormJson,
formError,
} = useFormJson(formUUID, formJson, encounterUUID || encounterUuid, formSessionIntent);
if (handleConfirmQuestionDeletion) functionStore.setState({ handleConfirmQuestionDeletion });

const { t } = useTranslation();
const formSessionDate = useMemo(() => new Date(), []);
Expand Down Expand Up @@ -270,91 +260,93 @@ const FormEngine: React.FC<FormProps> = ({
setIsFormDirty(props.dirty);

return (
<Form className={classNames('cds--form', styles.formEngine)} ref={ref}>
{isLoadingPatient || isLoadingFormJson ? (
<Loader />
) : (
<div className={styles.container}>
{isLoadingFormDependencies && (
<div className={styles.linearActivity}>
<div className={styles.indeterminate}></div>
</div>
)}
<div className={styles.body}>
{showSidebar && (
<Sidebar
isFormSubmitting={isSubmitting}
pagesWithErrors={pagesWithErrors}
scrollablePages={scrollablePages}
selectedPage={selectedPage}
mode={mode}
onCancel={onCancel}
handleClose={handleClose}
values={props.values}
setValues={props.setValues}
allowUnspecifiedAll={formJson.allowUnspecifiedAll}
defaultPage={formJson.defaultPage}
hideFormCollapseToggle={hideFormCollapseToggle}
/>
<HandleDeletionConfirmationContext.Provider value={{ handleConfirmQuestionDeletion }}>
<Form className={classNames('cds--form', styles.formEngine)} ref={ref}>
{isLoadingPatient || isLoadingFormJson ? (
<Loader />
) : (
<div className={styles.container}>
{isLoadingFormDependencies && (
<div className={styles.linearActivity}>
<div className={styles.indeterminate}></div>
</div>
)}
<div className={styles.content}>
{showPatientBanner && <PatientBanner patient={patient} hideActionsOverflow />}
{refinedFormJson.markdown && (
<div className={styles.markdownContainer}>
<MarkdownWrapper markdown={refinedFormJson.markdown} />
</div>
)}
<div className={styles.contentBody}>
<EncounterForm
formJson={refinedFormJson}
patient={patient}
formSessionDate={formSessionDate}
provider={currentProvider}
role={encounterRole?.uuid}
location={location}
visit={visit}
values={props.values}
isFormExpanded={isFormExpanded}
sessionMode={sessionMode}
<div className={styles.body}>
{showSidebar && (
<Sidebar
isFormSubmitting={isSubmitting}
pagesWithErrors={pagesWithErrors}
scrollablePages={scrollablePages}
setAllInitialValues={setInitialValues}
allInitialValues={initialValues}
setScrollablePages={setScrollablePages}
setPagesWithErrors={setPagesWithErrors}
setIsLoadingFormDependencies={setIsLoadingFormDependencies}
setFieldValue={props.setFieldValue}
setSelectedPage={setSelectedPage}
handlers={handlers}
workspaceLayout={workspaceLayout}
isSubmitting={isSubmitting}
setIsSubmitting={setIsSubmitting}
selectedPage={selectedPage}
mode={mode}
onCancel={onCancel}
handleClose={handleClose}
values={props.values}
setValues={props.setValues}
allowUnspecifiedAll={formJson.allowUnspecifiedAll}
defaultPage={formJson.defaultPage}
hideFormCollapseToggle={hideFormCollapseToggle}
/>
</div>
{showButtonSet && (
<ButtonSet className={styles.minifiedButtons}>
<Button
kind="secondary"
onClick={() => {
onCancel && onCancel();
handleClose && handleClose();
hideFormCollapseToggle();
}}>
{mode === 'view' ? t('close', 'Close') : t('cancel', 'Cancel')}
</Button>
<Button type="submit" disabled={mode === 'view' || isSubmitting}>
{isSubmitting ? (
<InlineLoading description={t('submitting', 'Submitting') + '...'} />
) : (
<span>{`${t('save', 'Save')}`}</span>
)}
</Button>
</ButtonSet>
)}
<div className={styles.content}>
{showPatientBanner && <PatientBanner patient={patient} hideActionsOverflow />}
{refinedFormJson.markdown && (
<div className={styles.markdownContainer}>
<MarkdownWrapper markdown={refinedFormJson.markdown} />
</div>
)}
<div className={styles.contentBody}>
<EncounterForm
formJson={refinedFormJson}
patient={patient}
formSessionDate={formSessionDate}
provider={currentProvider}
role={encounterRole?.uuid}
location={location}
visit={visit}
values={props.values}
isFormExpanded={isFormExpanded}
sessionMode={sessionMode}
scrollablePages={scrollablePages}
setAllInitialValues={setInitialValues}
allInitialValues={initialValues}
setScrollablePages={setScrollablePages}
setPagesWithErrors={setPagesWithErrors}
setIsLoadingFormDependencies={setIsLoadingFormDependencies}
setFieldValue={props.setFieldValue}
setSelectedPage={setSelectedPage}
handlers={handlers}
workspaceLayout={workspaceLayout}
isSubmitting={isSubmitting}
setIsSubmitting={setIsSubmitting}
/>
</div>
{showButtonSet && (
<ButtonSet className={styles.minifiedButtons}>
<Button
kind="secondary"
onClick={() => {
onCancel && onCancel();
handleClose && handleClose();
hideFormCollapseToggle();
}}>
{mode === 'view' ? t('close', 'Close') : t('cancel', 'Cancel')}
</Button>
<Button type="submit" disabled={mode === 'view' || isSubmitting}>
{isSubmitting ? (
<InlineLoading description={t('submitting', 'Submitting') + '...'} />
) : (
<span>{`${t('save', 'Save')}`}</span>
)}
</Button>
</ButtonSet>
)}
</div>
</div>
</div>
</div>
)}
</Form>
)}
</Form>
</HandleDeletionConfirmationContext.Provider>
);
}}
</Formik>
Expand Down
6 changes: 0 additions & 6 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,3 @@ export interface PatientProgramPayload {
endDate?: string;
}>;
}

export interface HandleConfirmDeletionFunctionStore {
handleConfirmQuestionDeletion: {
(question: Readonly<FormField>): Promise<void>;
};
}

0 comments on commit 7cc4ac3

Please sign in to comment.