Skip to content

Commit

Permalink
(fix) Refactor login and location picker components (#614)
Browse files Browse the repository at this point in the history
  • Loading branch information
denniskigen authored Feb 22, 2023
1 parent 11b11ad commit 9e4bce8
Show file tree
Hide file tree
Showing 10 changed files with 138 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const ChooseLocation: React.FC<ChooseLocationProps> = ({
const referrer = state?.referrer;
const config = useConfig();
const { user } = useSession();
const { locationData, isLoading } = useLoginLocations(
const { locations, isLoading } = useLoginLocations(
config.chooseLocation.useLoginLocationTag
);

Expand Down Expand Up @@ -55,35 +55,29 @@ export const ChooseLocation: React.FC<ChooseLocationProps> = ({
[referrer, config.links.loginSuccess, returnToUrl]
);

// Handle cases where the location picker is disabled, there is only one
// location, or there are no locations.
// Handle cases where the location picker is disabled, there is only one location, or there are no locations.
useEffect(() => {
if (!isLoading) {
if (!config.chooseLocation.enabled || locationData?.length === 1) {
changeLocation(locationData[0]?.resource.id);
if (!config.chooseLocation.enabled || locations?.length === 1) {
changeLocation(locations[0]?.resource.id);
}
if (!isLoading && !locationData?.length) {
if (!isLoading && !locations?.length) {
changeLocation();
}
}
}, [
locationData,
locations,
user,
changeLocation,
config.chooseLocation.enabled,
isLoading,
]);

if (!isLoading && !user) {
navigate({ to: "${openmrsSpaBase}/login" });
return null;
}

if (!isLoading || !isLoginEnabled) {
return (
<LocationPicker
currentUser={user.display}
loginLocations={locationData ?? []}
currentUser={user?.display}
loginLocations={locations ?? []}
onChangeLocation={changeLocation}
isLoginEnabled={isLoginEnabled}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import {
openmrsFetch,
fhirBaseUrl,
FetchResponse,
reportError,
showNotification,
} from "@openmrs/esm-framework";
import useSwrInfinite from "swr/infinite";
import { LocationEntry, LocationResponse } from "../types";

interface LoginLocationData {
locationData: Array<LocationEntry>;
locations: Array<LocationEntry>;
isLoading: boolean;
totalResults: number;
hasMore: boolean;
Expand All @@ -19,22 +20,21 @@ interface LoginLocationData {
) => Promise<FetchResponse<LocationResponse>[]>;
}

const fhirLocationUrl = `${fhirBaseUrl}/Location?_summary=data`;

export function useLoginLocations(
useLoginLocationTag: boolean,
count: number = 0,
searchQuery: string = ""
): LoginLocationData {
const getUrl = (page, prevPageData: FetchResponse<LocationResponse>) => {
const { t } = useTranslation();
function constructUrl(page, prevPageData: FetchResponse<LocationResponse>) {
if (
prevPageData &&
!prevPageData?.data?.link?.some((link) => link.relation === "next")
) {
return null;
}

let url = fhirLocationUrl;
let url = `${fhirBaseUrl}/Location?_summary=data`;

if (count) {
url += `&_count=${count}`;
Expand All @@ -53,24 +53,28 @@ export function useLoginLocations(
}

return url;
};
}

const { data, isValidating, setSize, error } = useSwrInfinite<
const { data, isLoading, isValidating, setSize, error } = useSwrInfinite<
FetchResponse<LocationResponse>,
Error
>(getUrl, openmrsFetch);
>(constructUrl, openmrsFetch);

if (error) {
console.error(error);
reportError(error);
showNotification({
title: t("errorLoadingLoginLocations", "Error loading login locations"),
kind: "error",
critical: true,
description: error?.message,
});
}

const memoizedLocationData = useMemo(() => {
const memoizedLocations = useMemo(() => {
return {
locationData: data
? [].concat(...data?.map((resp) => resp?.data?.entry ?? []))
locations: data?.length
? data?.flatMap((entries) => entries?.data?.entry ?? [])
: null,
isLoading: !data && !error,
isLoading,
totalResults: data?.[0]?.data?.total ?? null,
hasMore: data?.length
? data?.[data.length - 1]?.data?.link.some(
Expand All @@ -80,7 +84,7 @@ export function useLoginLocations(
loadingNewData: isValidating,
setPage: setSize,
};
}, [data, error, isValidating, setSize, searchQuery]);
}, [isLoading, data, isValidating, setSize]);

return memoizedLocationData;
return memoizedLocations;
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
currentLocationUuid,
isLoginEnabled,
}) => {
const { t } = useTranslation();
const config = useConfig();
const searchTimeout = 300;
const inputRef = useRef();
const { chooseLocation } = config;
const { t } = useTranslation();
const [pageSize, setPageSize] = useState<number>(chooseLocation.numberToShow);
const userDefaultLoginLocation: string = "userDefaultLoginLocationKey";
const getDefaultUserLoginLocation = (): string => {
const userDefaultLoginLocation = "userDefaultLoginLocationKey";

const getDefaultUserLoginLocation = () => {
const userLocation = window.localStorage.getItem(
`${userDefaultLoginLocation}${currentUser}`
);
Expand All @@ -45,13 +47,28 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
);
return isValidLocation ? userLocation : "";
};
const [activeLocation, setActiveLocation] = useState<string>(
getDefaultUserLoginLocation() ?? ""
);
const [searchTerm, setSearchTerm] = useState("");

const [activeLocation, setActiveLocation] = useState(() => {
if (currentLocationUuid && hideWelcomeMessage) {
return currentLocationUuid;
}

return getDefaultUserLoginLocation() ?? "";
});

const [isSubmitting, setIsSubmitting] = useState(false);

const [searchTerm, setSearchTerm] = useState(() => {
if (isSubmitting && inputRef.current) {
let searchInput: HTMLInputElement = inputRef.current;
searchInput.value = "";
setSearchTerm(null);
}
return "";
});

const {
locationData,
locations,
isLoading,
hasMore,
totalResults,
Expand All @@ -63,16 +80,12 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
searchTerm
);

const [isSubmitting, setIsSubmitting] = useState(false);
const inputRef = useRef();
const searchTimeout = 300;

useEffect(() => {
if (isSubmitting) {
onChangeLocation(activeLocation);
setIsSubmitting(false);
const [pageSize, setPageSize] = useState(() => {
if (!isLoading && totalResults && chooseLocation.numberToShow) {
return Math.min(chooseLocation.numberToShow, totalResults);
}
}, [isSubmitting, activeLocation, onChangeLocation]);
return chooseLocation.numberToShow;
});

useEffect(() => {
if (activeLocation) {
Expand All @@ -84,24 +97,11 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
}, [activeLocation, currentUser]);

useEffect(() => {
if (currentLocationUuid && hideWelcomeMessage) {
setActiveLocation(currentLocationUuid);
}
}, [currentLocationUuid, hideWelcomeMessage]);

useEffect(() => {
if (isSubmitting && inputRef.current) {
let searchInput: HTMLInputElement = inputRef.current;
searchInput.value = "";
setSearchTerm(null);
}
}, [isSubmitting]);

useEffect(() => {
if (!isLoading && totalResults && chooseLocation.numberToShow) {
setPageSize(Math.min(chooseLocation.numberToShow, totalResults));
if (isSubmitting) {
onChangeLocation(activeLocation);
setIsSubmitting(false);
}
}, [isLoading, totalResults, chooseLocation.numberToShow]);
}, [isSubmitting, activeLocation, onChangeLocation]);

const search = debounce((location: string) => {
setActiveLocation("");
Expand All @@ -113,7 +113,7 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
setIsSubmitting(true);
};

// Infinte scrolling
// Infinite scroll
const observer = useRef(null);
const loadingIconRef = useCallback(
(node) => {
Expand Down Expand Up @@ -162,7 +162,7 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
{!isLoading ? (
<>
<div className={styles.locationResultsContainer}>
{locationData?.length > 0 && (
{locations?.length > 0 && (
<RadioButtonGroup
valueSelected={activeLocation}
orientation="vertical"
Expand All @@ -171,7 +171,7 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
setActiveLocation(ev.toString());
}}
>
{locationData.map((entry) => (
{locations.map((entry) => (
<RadioButton
className={styles.locationRadioButton}
key={entry.resource.id}
Expand All @@ -182,7 +182,7 @@ const LocationPicker: React.FC<LocationPickerProps> = ({
))}
</RadioButtonGroup>
)}
{locationData?.length === 0 && (
{locations?.length === 0 && (
<div className={styles.emptyState}>
<p className={styles.locationNotFound}>
{t("noResultsToDisplay", "No results to display")}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
}

.paddedContainer {
padding: spacing.$spacing-06;
padding: spacing.$spacing-06 spacing.$spacing-06 spacing.$spacing-05;
}

.locationCard {
Expand All @@ -31,7 +31,7 @@

.welcomeMessage {
@extend .bodyLong01;
margin-top: spacing.$spacing-01;
margin-top: spacing.$spacing-03;
color: $color-gray-70;
}

Expand All @@ -52,7 +52,6 @@
.locationResultsContainer {
display: flex;
overflow-y: auto;
margin-top: spacing.$spacing-05;
padding: 0rem spacing.$spacing-01 0rem;
}

Expand Down
Loading

0 comments on commit 9e4bce8

Please sign in to comment.