export function useProfiles()

in frontend/src/hooks/api/profile.ts [42:105]


export function useProfiles(): SWRResponse<ProfilesData, unknown> & {
  update: ProfileUpdateFn;
  setSubdomain: SetSubdomainFn;
} {
  const profiles = useSWR("/profiles/", profileFetcher, {
    revalidateOnFocus: false,
    onErrorRetry: (
      error: unknown | FetchError,
      key: string,
      // SWR's type definitions do not expose the type required here, at the
      // time of writing, and they're not reconcilable with anything other than
      // `any`. Since we're just passing on the value unmodified anyway, this
      // should not be a problem:
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      config: any,
      revalidate: Parameters<typeof SWRConfig.defaultValue.onErrorRetry>[3],
      revalidateOpts: Parameters<typeof SWRConfig.defaultValue.onErrorRetry>[4],
    ) => {
      if (error instanceof FetchError && error.response.status === 401) {
        // When the user is not logged in, this API returns a 401.
        // If so, do not retry.
        return;
      }
      SWRConfig.defaultValue.onErrorRetry(
        error,
        key,
        config,
        revalidate,
        revalidateOpts,
      );
    },
  }) as SWRResponse<ProfilesData, FetchError>;

  /**
   * Update a user's profile. Note that setting a subdomain currently requires
   * the use of `setSubdomain`, because that calls a special API endpoint that
   * will also hash the subdomain to prevent duplicate subdomains.
   */
  const update: ProfileUpdateFn = async (id, data) => {
    const response = await apiFetch(`/profiles/${id}/`, {
      method: "PATCH",
      body: JSON.stringify(data),
    });
    profiles.mutate();
    return response;
  };
  const setSubdomain: SetSubdomainFn = async (subdomain) => {
    const response = await authenticatedFetch("/accounts/profile/subdomain", {
      method: "POST",
      body: new URLSearchParams({ subdomain: subdomain }).toString(),
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    profiles.mutate();
    return response;
  };

  return {
    ...profiles,
    update: update,
    setSubdomain: setSubdomain,
  };
}