@apollo/client#useQuery TypeScript Examples
The following examples show how to use
@apollo/client#useQuery.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: useGetQueryDataByFieldName.ts From apollo-cache-policies with Apache License 2.0 | 6 votes |
useGetQueryDataByFieldName = <FieldType>(query: DocumentNode, fieldName: string) => {
const result = useQuery<Record<string, FieldType>>(query, {
fetchPolicy: 'cache-only',
});
const requiredDataResult = {
...result,
data: result?.data?.[fieldName],
};
type RequiredDataResult = typeof requiredDataResult & { data: FieldType };
return requiredDataResult as RequiredDataResult;
}
Example #2
Source File: App.tsx From Full-Stack-React-TypeScript-and-Node with MIT License | 6 votes |
function App() {
const { data: categoriesData } = useQuery(GetAllCategories);
const { execMe, updateMe } = useRefreshReduxMe();
const dispatch = useDispatch();
useEffect(() => {
execMe();
}, [execMe]);
useEffect(() => {
updateMe();
}, [updateMe]);
useEffect(() => {
if (categoriesData && categoriesData.getAllCategories) {
dispatch({
type: ThreadCategoriesType,
payload: categoriesData.getAllCategories,
});
}
}, [dispatch, categoriesData]);
const renderHome = (props: any) => <Home {...props} />;
const renderThread = (props: any) => <Thread {...props} />;
const renderUserProfile = (props: any) => <UserProfile {...props} />;
return (
<Switch>
<Route exact={true} path="/" render={renderHome} />
<Route path="/categorythreads/:categoryId" render={renderHome} />
<Route path="/thread/:id?" render={renderThread} />
<Route path="/userprofile/:id" render={renderUserProfile} />
</Switch>
);
}
Example #3
Source File: SpaceXApp.tsx From Intro_to_React with GNU General Public License v2.0 | 6 votes |
SpaceXApp = () => {
const { loading, error, data } = useQuery(LAUNCHES)
if (loading) {
return <div>...loading </div>
}
if (error) {
return <div>...error </div>
}
const { launchesPast } = data
console.log(launchesPast)
return (
<main className={styles.container}>
{launchesPast.map((launch: any) => (
<section
key={launch.mission_name}
className={styles.card}
>
<header>
<h1>{launch.mission_name}</h1>
<h2>by {launch.rocket.rocket_name}</h2>
<p>{launch.rocket.launch_date_unix}</p>
{launch.links.mission_patch_small != null && (
<img className={styles.icon} alt="mission" src={launch.links.mission_patch_small} />
)}
</header>
{launch.links.flickr_images.slice(0, 2).map((url: string) => (
<img key={url} className={styles.photo} alt="mission" src={url} />
))}
</section>
))}
</main>
)
}
Example #4
Source File: RowTransactions.tsx From devex with GNU General Public License v3.0 | 6 votes |
RowTransactions: React.FC<IProps> = ({ addr }) => {
const ACCOUNT_TRANSACTIONS = gql`
query GetTransactions($addr: String!) {
txnsByAddr(addr: $addr) {
ID
}
}
`;
const { loading, error, data } = useQuery(ACCOUNT_TRANSACTIONS, {
variables: { addr },
});
if (data) {
console.log(data);
}
return loading ? (
<div className="center-spinner">
<Spinner animation="border" />
</div>
) : (
<Row>
<Col>
<div className="address-detail">
<span>Transactions:</span>
<span>{data.txnsByAddr.length}</span>
</div>
</Col>
</Row>
);
}
Example #5
Source File: SyncWithGithubPage.tsx From amplication with Apache License 2.0 | 6 votes |
function SyncWithGithubPage({ match }: Props) {
const { application } = match.params;
const { data, error, refetch } = useQuery<{ app: AppWithGitRepository }>(
GET_APP_GIT_REPOSITORY,
{
variables: {
appId: application,
},
}
);
useNavigationTabs(application, NAVIGATION_KEY, match.url, `GitHub`);
const errorMessage = formatError(error);
return (
<PageContent>
<div className={CLASS_NAME}>
<div className={`${CLASS_NAME}__header`}>
<Icon icon="github" size="xlarge" />
<h1>Sync with GitHub</h1>
</div>
<div className={`${CLASS_NAME}__message`}>
Enable sync with GitHub to automatically push the generated code of
your application and create a Pull Request in your GitHub repository
every time you commit your changes.
</div>
{data?.app && <AuthAppWithGit app={data.app} onDone={refetch} />}
<Snackbar open={Boolean(error)} message={errorMessage} />
</div>
</PageContent>
);
}
Example #6
Source File: Apollo.ts From graphql-ts-client with MIT License | 6 votes |
export function useTypedQuery<
TData extends object,
TVariables extends object
>(
fetcher: Fetcher<"Query", TData, TVariables>,
options?: QueryHookOptions<TData, TVariables> & {
readonly operationName?: string,
readonly registerDependencies?: boolean | { readonly fieldDependencies: readonly Fetcher<string, object, object>[] }
}
) : QueryResult<TData, TVariables> {
const body = requestBody(fetcher);
const [operationName, request] = useMemo<[string, DocumentNode]>(() => {
const operationName = options?.operationName ?? `query_${util.toMd5(body)}`;
return [operationName, gql`query ${operationName}${body}`];
}, [body, options?.operationName]);
const [dependencyManager, config] = useContext(dependencyManagerContext);
const register = options?.registerDependencies !== undefined ? !!options.registerDependencies : config?.defaultRegisterDependencies ?? false;
if (register && dependencyManager === undefined) {
throw new Error("The property 'registerDependencies' of options requires <DependencyManagerProvider/>");
}
useEffect(() => {
if (register) {
dependencyManager!.register(
operationName,
fetcher,
typeof options?.registerDependencies === 'object' ? options?.registerDependencies?.fieldDependencies : undefined
);
return () => { dependencyManager!.unregister(operationName); };
}// eslint-disable-next-line
}, [register, dependencyManager, operationName, options?.registerDependencies, request]); // Eslint disable is required, becasue 'fetcher' is replaced by 'request' here.
const response = useQuery<TData, TVariables>(request, options);
const responseData = response.data;
const newResponseData = useMemo(() => util.exceptNullValues(responseData), [responseData]);
return newResponseData === responseData ? response : { ...response, data: newResponseData };
}
Example #7
Source File: MainLayout.tsx From opensaas with MIT License | 6 votes |
MainDashboard = () => {
const { loading, error, data } = useQuery(REQUESTS);
if (loading) {
return <p>Loading...</p>;
}
if (error) {
console.error(error);
}
const requests = data?.requests.length ? data.requests : MOCK_REQUESTS;
return <Dashboard requests={requests} />;
}
Example #8
Source File: index.tsx From nextjs-strapi-boilerplate with MIT License | 6 votes |
FeedsPageComponent = () => {
const {
loading: fetchFeedsFetching,
error: fetchFeedsError,
data: fetchFeedsData,
} = useQuery(feedsQuery, { pollInterval: 5000 });
if (fetchFeedsFetching) {
return <Loader />;
}
if (fetchFeedsError) {
return <p>Error: {fetchFeedsError.message}</p>;
}
return (
<Stack spacing={8}>
<Box>
<AddNewFeedForm />
</Box>
{fetchFeedsData.feeds.map((feed: IFeed) => {
return (
<Box key={feed.id}>
<Feed feed={feed} />
</Box>
);
})}
</Stack>
);
}
Example #9
Source File: CollectionContact.tsx From glific-frontend with GNU Affero General Public License v3.0 | 6 votes |
CollectionContact: React.FC<CollectionContactProps> = (
props: CollectionContactProps
) => {
const { t } = useTranslation();
const { match } = props;
const collectionId = match.params.id;
const collection = useQuery(GET_COLLECTION, {
variables: { id: collectionId },
fetchPolicy: 'cache-and-network',
});
const title = collection.data ? collection.data.group.group.label : t('Collection');
let users;
let description;
if (collection.data) {
users = collection.data.group.group.users;
description = collection.data.group.group.description;
}
return (
<div className={styles.CollectionContactContainer}>
<div className={styles.ContactList}>
<CollectionContactList {...props} title={title} />
</div>
<div className={styles.CollectionDescription}>
<CollectionDescription
users={users}
description={description}
collectionId={collectionId}
/>
</div>
</div>
);
}
Example #10
Source File: useLesson.tsx From nyxo-app with GNU General Public License v3.0 | 6 votes |
useLesson = (
slug?: string
): QueryResult<LessonData, LessonVariables> => {
const locale = I18n.locale === 'en' ? 'en-US' : 'fi-FI'
return useQuery<LessonData, LessonVariables>(GET_LESSON, {
variables: { language: locale, slug }
})
}
Example #11
Source File: WrappedSafeComponent.tsx From liferay-grow with MIT License | 6 votes |
WrappedSafeComponent = <T,>({ children, options, query, }: WrappedSafeComponentProps<T>): React.ReactElement => { const { data, error, loading, refetch, variables } = useQuery<T>( query, options, ); const response: Response<T> = { data, refetch, variables, }; try { if (error) { console.error(error); // eslint-disable-line no-console return <div>Sorry, an error occurred.</div>; } if (loading) { return <ClayLoadingIndicator className="mt-4" />; } } catch (error) { console.error(error); // eslint-disable-line no-console } return children(response); }
Example #12
Source File: Rooms.tsx From dh-web with GNU General Public License v3.0 | 6 votes |
RoomListDataContainer: FC = () => {
const { loading, data, error, subscribeToMore } = useQuery<RoomListQuery>(
ROOM_LIST_QUERY,
{ fetchPolicy: "cache-first" }
);
return (
<RoomList loading={loading} error={error} data={data}
roomUpdates={() => subscribeToMore<RoomListSubscription>({
onError: console.error,
document: ROOM_LIST_SUBSCRIPTION, variables: {}, updateQuery: (previous, { subscriptionData }) => {
if (!subscriptionData) return previous;
if (subscriptionData.data.roomChange.event === "CREATE") {
return {
...previous,
rooms: [...previous.rooms, subscriptionData.data.roomChange.room]
};
}
if (subscriptionData.data.roomChange.event === "DELETE") {
return {
...previous,
rooms: previous.rooms.filter(room => room.id !== subscriptionData.data.roomChange.room.id)
};
}
if (subscriptionData.data.roomChange.event === "UPDATE") {
return {
...previous,
rooms: previous.rooms.map(room => room.id === subscriptionData.data.roomChange.room.id ? subscriptionData.data.roomChange.room : room)
};
}
return previous;
}
})} />
);
}
Example #13
Source File: useBlockTimesForDates.ts From mStable-apps with GNU Lesser General Public License v3.0 | 6 votes |
useBlockTimesForDates = (dates: Date[]): BlockTime[] => {
const { blocks: client } = useApolloClients()
const blocksDoc = useBlockTimestampsDocument(dates)
const query = useQuery<{
[timestamp: string]: [] | [{ number: number }]
}>(blocksDoc, { fetchPolicy: 'cache-first', client })
return useMemo(() => {
const filtered = Object.entries(query.data ?? {}).filter(([, value]) => !!value[0]?.number) as [string, [{ number: number }]][]
return filtered
.map(([key, [{ number }]]) => ({
timestamp: getKeyTimestamp(key),
number,
}))
.sort((a, b) => (a.timestamp > b.timestamp ? 1 : -1))
}, [query.data])
}
Example #14
Source File: PostList.tsx From next-page-tester with MIT License | 6 votes |
export function PostList() {
const { loading, data } = useQuery<{
allPosts: Post[];
}>(ALL_POSTS_QUERY, { variables: allPostsQueryVars });
if (!data || loading) return <div>Loading</div>;
const { allPosts } = data;
return (
<section>
<ul>
{allPosts.map((post, index) => (
<li key={post.id}>
<div>
<span>{index + 1}. </span>
<Link href={post.url}>
<a href={post.url}>{post.title}</a>
</Link>
</div>
</li>
))}
</ul>
</section>
);
}
Example #15
Source File: index.tsx From nouns-monorepo with GNU General Public License v3.0 | 6 votes |
PastAuctions: React.FC = () => {
const latestAuctionId = useAppSelector(state => state.onDisplayAuction.lastAuctionNounId);
const { data } = useQuery(latestAuctionsQuery());
const dispatch = useAppDispatch();
useEffect(() => {
data && dispatch(addPastAuctions({ data }));
}, [data, latestAuctionId, dispatch]);
return <></>;
}
Example #16
Source File: GameDetails.tsx From game-store-monorepo-app with MIT License | 6 votes |
GameDetails: React.FC = () => {
const { setTitle } = React.useContext(NavigationContext);
const { id } = useParams<GameDetailRouteParams>();
const queryParams: GameDetailsQueryParams = React.useMemo(() => {
return {
variables: {
id: id ? parseInt(id) : 0,
},
};
}, [id]);
const { data, loading } = useQuery<GameDetailsQueryResponse>(GET_GAME_DETAILS, queryParams);
const gameDetails = data?.gameDetails;
React.useEffect(() => {
setTitle(gameDetails?.name || '...');
}, [gameDetails?.name, setTitle]);
return (
<>
<GeneralInformation data={gameDetails} isLoading={loading} />
<MediaPreviewTab data={gameDetails} isLoading={loading} />
<Description data={gameDetails?.description} isLoading={loading} />
<GamesInGenres data={gameDetails?.genres} />
<Tags data={gameDetails?.tags} isLoading={loading} />
{gameDetails?.id && <GameSeries gameId={gameDetails.id} />}
<ScrollToTop />
</>
);
}
Example #17
Source File: use.imerative.query.ts From ui with GNU Affero General Public License v3.0 | 6 votes |
useImperativeQuery: <TData, TVariables>(
query: DocumentNode
) => (variables: TVariables) => Promise<ApolloQueryResult<TData>> = (query) => {
const { refetch } = useQuery(query, { skip: true })
return useCallback(
(variables) => {
return refetch(variables)
},
[refetch]
)
}
Example #18
Source File: index.tsx From surveyo with Apache License 2.0 | 6 votes |
export default function Page() {
const {id} = useParams();
const {loading, error, data} = useQuery<GetForm, GetFormVariables>(GET_FORM, {
variables: {id},
});
if (loading) {
return <PageLoading />;
}
if (error) {
console.error(error);
return <Result500 />;
}
if (!data?.getForm) {
return <Result404 />;
}
return <SyForm data={data.getForm} />;
}
Example #19
Source File: useCategories.ts From magento_react_native_graphql with MIT License | 6 votes |
useCategories = ({ categoryId: id }: Props): Result => {
const { loading, data, error } = useQuery<
CategoriesDataType,
GetCategoriesVars
>(GET_CATEGORIES, {
variables: {
id,
},
});
return {
categories: data?.categoryList?.[0]?.children,
loading,
error,
};
}
Example #20
Source File: use-feature-flags.ts From beancount-mobile with MIT License | 6 votes |
useFeatureFlags = (userId: string): FlagMap => {
const { data } = useQuery<FeatureFlags>(getFeatureFlags, {
variables: {
userId,
},
});
return {
spendingReportSubscription: data?.featureFlags?.spendingReportSubscription,
};
}
Example #21
Source File: useProductDetailQuery.tsx From nft-marketplace with European Union Public License 1.2 | 6 votes |
useProductDetailQuery = ({ slug }) => {
const { data, loading, error } = useQuery(ProductDetailQuery, {
variables: { slug },
});
return {
product: data?.product,
loading,
error,
};
}
Example #22
Source File: Detail.tsx From Intro_to_React with GNU General Public License v2.0 | 5 votes |
Detail = () => {
const { mission_id } = useParams<{ mission_id: string }>()
const { loading, error, data } = useQuery(QUERY, {
variables: { id: mission_id },
})
if (loading) {
return <div>...loading </div>
}
if (error) {
return <div>...error </div>
}
const { launch } = data
console.log(launch)
return (
<motion.div
style={{ padding: "3rem", backgroundColor: "#333456", color: "#bbbfca" }}
initial="initial"
animate="in"
exit="out"
variants={variant}
>
<header>
<h1>{launch.mission_name}</h1>
<h2>by {launch.rocket.rocket_name}</h2>
<p>{launch.launch_date_utc}</p>
<p>{launch.details}</p>
{launch.links.mission_patch_small != null && (
<img style={{maxWidth: "5rem"}} alt="mission" src={launch.links.mission_patch_small} />
)}
</header>
{launch.links.flickr_images.slice(0, 2).map((url: string) => (
<img style={{maxWidth: "5rem"}} key={url} alt="mission" src={url} />
))}
</motion.div>
)
}
Example #23
Source File: EntitiesTile.tsx From amplication with Apache License 2.0 | 5 votes |
function EntitiesTile({ applicationId }: Props) {
const history = useHistory();
const { data, loading } = useQuery<{
entities: models.Entity[];
}>(GET_ENTITIES, {
variables: {
id: applicationId,
},
});
const { trackEvent } = useTracking();
const handleClick = useCallback(
(event) => {
trackEvent(EVENT_DATA);
history.push(`/${applicationId}/entities`);
},
[history, trackEvent, applicationId]
);
return (
<Panel
className={`${CLASS_NAME}`}
clickable
onClick={handleClick}
panelStyle={EnumPanelStyle.Bordered}
>
<div className={`${CLASS_NAME}__content`}>
<div className={`${CLASS_NAME}__content__details`}>
<h2>Entities</h2>
Define the data model of you application with data entities and
role‑based access.
{loading ? (
<CircularProgress />
) : (
<span className={`${CLASS_NAME}__content__details__summary`}>
<Icon icon="database" size="medium" />
{data?.entities.length}
{data?.entities.length > 1 ? " entities" : " entity"}
</span>
)}
</div>
<SvgThemeImage image={EnumImages.Entities} />
</div>
</Panel>
);
}
Example #24
Source File: index.ts From graphql-typed-document-node with MIT License | 5 votes |
result = useQuery(RatesDocument, {
variables: {
currency: "USD",
},
})
Example #25
Source File: StatusBar.tsx From glific-frontend with GNU Affero General Public License v3.0 | 5 votes |
StatusBar: React.FC<StatusBarProps> = () => {
const variables = { organizationId: getUserSession('organizationId') };
// get gupshup balance
const { data: balanceData } = useQuery(BSPBALANCE, {
variables,
fetchPolicy: 'cache-only',
});
if (!balanceData) {
return null;
}
const { balance } = JSON.parse(balanceData.bspbalance);
let statusMessage;
if (balance < 1 && balance > 0) {
statusMessage =
'Please recharge your Gupshup wallet immediately to continue sending messages. Users will not receive the messages that get stuck during this time.';
} else if (balance <= 0) {
statusMessage =
'All the outgoing messages have been suspended. Please note: on recharging, the messages that were stuck will not be sent.';
}
// TODOS: need to implement this once backend implements this feature
// const limitReached = false;
// if (limitReached) {
// statusMessage =
// 'You have reached today’s rate limit for sending HSM templates to your users. Your rate limit will be refreshed tomorrow. Please check again later.';
// }
if (statusMessage) {
return (
<div className={styles.StatusMessage}>
<span className={styles.StatusTitle}>Attention! </span>
{statusMessage}
</div>
);
}
return null;
}
Example #26
Source File: useWeek.ts From nyxo-app with GNU General Public License v3.0 | 5 votes |
useWeek = (slug: string): QueryResult<WeekData, WeekVariables> => {
const locale = I18n.locale === 'en' ? 'en-US' : 'fi-FI'
return useQuery<WeekData, WeekVariables>(GET_WEEK, {
variables: { language: locale, slug }
})
}
Example #27
Source File: useSiteSettings.ts From lexicon with MIT License | 5 votes |
export function useSiteSettings() {
let { data, loading, error, refetch } = useQuery<Site>(SITE, {
notifyOnNetworkStatusChange: true,
});
const {
canTagTopics,
canCreateTag,
canSignUp,
authorizedExtensions,
uncategorizedCategoryId = DEFAULT_CHANNEL.id,
minSearchLength,
taggingEnabled,
maxTagLength,
maxTagsPerTopic,
maxUsernameLength,
minUsernameLength,
minPasswordLength,
fullNameRequired,
topicFlagTypes,
postActionTypes,
} = data?.site || {};
return {
canTagTopics,
canCreateTag,
canSignUp,
authorizedExtensions,
uncategorizedCategoryId,
minSearchLength,
taggingEnabled,
maxTagLength,
maxTagsPerTopic,
maxUsernameLength,
minUsernameLength,
minPasswordLength,
fullNameRequired,
topicFlagTypes,
postActionTypes,
loading,
error,
refetch,
};
}
Example #28
Source File: FriendsList.tsx From dh-web with GNU General Public License v3.0 | 5 votes |
FriendsList: FC = () => {
const { loading, data, error } = useQuery<FriendsQuery>(
FRIENDS_QUERY,
{ fetchPolicy: "network-only" }
);
const theme = useTheme();
const three = useMediaQuery(`(min-width:${theme.breakpoints.three + 1}px)`);
if (loading || error) {
return (
<Wrapper>
{
three &&
<Title>
People
<SubTitle>
ONLINE
</SubTitle>
</Title>
}
</Wrapper>
);
}
return (
<Wrapper>
{
three &&
<Title>
People
<SubTitle>
ONLINE
</SubTitle>
</Title>
}
{
data.me.following.map(({ following: user }) => (
<Line key={user.id}>
<ProfilePicture>
<img src={user.avatar} alt="User Avatar" />
</ProfilePicture>
{ user && <Dot />}
{ three &&
<UserName>
{user.username}
{user.current_room &&
<UserRoom>
{user.current_room.room.name}
</UserRoom>
}
</UserName>
}
</Line>
))
}
</Wrapper>
);
}
Example #29
Source File: index.tsx From tinyhouse with MIT License | 5 votes |
export function Listing() {
const [bookingsPage, setBookingsPage] = useState(1);
const [checkInDate, setCheckInDate] = useState<Moment | null>(null);
const [checkOutDate, setCheckOutDate] = useState<Moment | null>(null);
const { listingId } = useParams();
const { loading, data, error } = useQuery<ListingData, ListingVariables>(
LISTING,
{
variables: {
id: listingId ?? "",
bookingsPage: bookingsPage,
limit: PAGE_LIMIT,
},
}
);
if (loading) {
return (
<Content className="listing">
<PageSkeleton />
</Content>
);
}
if (error) {
return (
<Content className="listing">
<ErrorBanner description="This listing may not exist or we've encountered an error. Please try again soon!" />
<PageSkeleton />
</Content>
);
}
const listing = data ? data.listing : null;
const listingBookings = listing ? listing.bookings : null;
const listingDetailsElement = listing ? (
<ListingDetails listing={listing} />
) : null;
const listingBookingsElement = listingBookings ? (
<ListingBookings
listingBookings={listingBookings}
bookingsPage={bookingsPage}
limit={PAGE_LIMIT}
setBookingsPage={setBookingsPage}
/>
) : null;
const listingCreateBookingElement = listing ? (
<ListingCreateBooking
price={listing.price}
checkInDate={checkInDate}
checkOutDate={checkOutDate}
setCheckInDate={setCheckInDate}
setCheckOutDate={setCheckOutDate}
/>
) : null;
return (
<Content className="listing">
<Row gutter={24} justify="space-between">
<Col xs={24} lg={14}>
{listingDetailsElement}
{listingBookingsElement}
</Col>
<Col xs={24} lg={10}>
{listingCreateBookingElement}
</Col>
</Row>
</Content>
);
}