| 1 | import { createAsyncThunk } from "@reduxjs/toolkit"; |
| 2 | import { setSelectedProfile } from "../slices/profilesSlice"; |
| 3 | import { ThunkApiType } from "../store"; |
| 4 | |
| 5 | /** |
| 6 | * If there is a hub profile, select it. |
| 7 | * Used primarily after onboarding when a new profile is created and we |
| 8 | * want to switch to it immediately |
| 9 | */ |
| 10 | export const selectFirstHubProfile = createAsyncThunk< |
| 11 | void, |
| 12 | undefined, |
| 13 | ThunkApiType |
| 14 | >("selectFirstHubProfile", async (_, { dispatch, extra, getState }) => { |
| 15 | let attempts = 0; |
| 16 | const maxAttempts = 3; |
| 17 | |
| 18 | const findAndSelectProfile = () => { |
| 19 | const state = getState(); |
| 20 | |
| 21 | const currentOrgProfiles = state.profiles.organizations.find( |
| 22 | (org) => org.id === (state.profiles.selectedOrganizationId ?? "personal"), |
| 23 | ); |
| 24 | |
| 25 | const firstHubProfile = currentOrgProfiles?.profiles.find( |
| 26 | (profile) => profile.profileType === "platform", |
| 27 | ); |
| 28 | |
| 29 | if (firstHubProfile) { |
| 30 | dispatch(setSelectedProfile(firstHubProfile.id)); |
| 31 | extra.ideMessenger.post("didChangeSelectedProfile", { |
| 32 | id: firstHubProfile.id, |
| 33 | }); |
| 34 | return true; |
| 35 | } |
| 36 | |
| 37 | return false; |
| 38 | }; |
| 39 | |
| 40 | // Try immediately first |
| 41 | if (findAndSelectProfile()) { |
| 42 | return; |
| 43 | } |
| 44 | |
| 45 | // If not found, poll every second for up to maxAttempts |
| 46 | return new Promise<void>((resolve) => { |
| 47 | const interval = setInterval(() => { |
| 48 | attempts++; |
| 49 | |
| 50 | if (findAndSelectProfile() || attempts >= maxAttempts) { |
| 51 | clearInterval(interval); |
| 52 | resolve(); |
| 53 | } |
| 54 | }, 1000); |
| 55 | }); |
| 56 | }); |