Skip to content

Commit

Permalink
Fix medplum.isLoading issue
Browse files Browse the repository at this point in the history
  • Loading branch information
fjsj committed Feb 8, 2025
1 parent 2e31ff6 commit f47ced9
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions app/(app)/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,59 @@
import { MedplumClient } from "@medplum/core";
import { useMedplumContext } from "@medplum/react-hooks";
import { Redirect, Slot } from "expo-router";
import { Redirect, router, Slot } from "expo-router";
import { useEffect } from "react";

import { LoadingScreen } from "@/components/LoadingScreen";
import { PractitionerBanner } from "@/components/PractitionerBanner";
import { ChatProvider } from "@/contexts/ChatContext";
import { useNotifications } from "@/contexts/NotificationsContext";

async function retryMedplumProfile(medplum: MedplumClient) {
// If profile is already loaded, do nothing:
if (!medplum.isLoading()) {
return;
}
// If Medplum is not initialized, check again later:
if (!medplum.isInitialized) {
setTimeout(() => retryMedplumProfile(medplum), 1000);
return;
}

// The only way to check if profile fetch failed is to await for getProfileAsync
try {
await medplum.getProfileAsync();
} catch {
// If profile fetch failed, force profile reload by calling setActiveLogin,
// as it's the only way to clean up the internal profilePromise,
// otherwise MedplumClient stays stuck in loading state
const activeLogin = medplum.getActiveLogin();
if (activeLogin) {
medplum.setActiveLogin(activeLogin);
// Ensure profile fetch after 1 second:
setTimeout(() => retryMedplumProfile(medplum), 1000);
} else {
// If there's no active login, redirect to sign-in:
medplum.clearActiveLogin();
router.replace("/sign-in");
}
}
}

export default function AppLayout() {
const { medplum, profile } = useMedplumContext();
const { setUpPushNotifications } = useNotifications();
const isPractitioner = profile?.resourceType === "Practitioner";

// Ensure profile is loaded or loading,
// to avoid app getting stuck in medplum.isLoading() state
// when an error occurs in the internal profilePromise (due to server or network issues)
useEffect(() => {
retryMedplumProfile(medplum);
}, [medplum]);

// Set up push notifications when user is logged in
useEffect(() => {
if (profile) {
// Set up push notifications when user is logged in
setUpPushNotifications();
}
}, [profile, setUpPushNotifications]);
Expand Down

0 comments on commit f47ced9

Please sign in to comment.