import { Config, store } from '@graphprotocol/hypergraph'; import { useQuery } from '@tanstack/react-query'; import { useSelector } from '@xstate/store/react'; import { gql, request } from 'graphql-request'; import { useEffect } from 'react'; import { useHypergraphApp } from '../HypergraphAppContext.js'; const publicSpacesQueryDocument = gql` query Spaces($memberId: UUID!) { spaces(filter: {members: {some: {memberSpaceId: {is: $memberId}}}}) { id page { name } } } `; type PublicSpacesQueryResult = { spaces: { id: string; page: { name: string; } | null; }[]; }; export const useSpaces = (params: { mode: 'public' | 'private' }) => { const identityAccountAddress = useSelector(store, (state) => state.context.identity?.accountAddress); const privyIdentityAccountAddress = useSelector(store, (state) => state.context.privyIdentity?.accountAddress); const accountAddress = identityAccountAddress ? identityAccountAddress : privyIdentityAccountAddress; const publicResult = useQuery({ queryKey: ['hypergraph-public-spaces', params.mode], queryFn: async () => { const result = await request( `${Config.getApiOrigin()}/graphql`, publicSpacesQueryDocument, { accountAddress, }, ); return result?.spaces ? result.spaces.map((space) => ({ id: space.id, name: space.page?.name, })) : []; }, enabled: params.mode === 'public' && !!accountAddress, }); const { isConnecting, listSpaces } = useHypergraphApp(); useEffect(() => { if (params.mode === 'private' && !isConnecting) { listSpaces(); } }, [params.mode, listSpaces, isConnecting]); const spaces = useSelector(store, (state) => state.context.spaces); const spacesLoadingIsPending = useSelector(store, (state) => state.context.spacesLoadingIsPending); if (params.mode === 'private') { return { data: spaces, isPending: spacesLoadingIsPending, }; } return publicResult; };