const COMMENTS_QUERY = gql`
query Comments($cursor: String) {
comments(first: 10, after: $cursor) {
edges {
node {
author
text
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
`;
function CommentsWithData() {
const { data, loading, fetchMore } = useQuery(COMMENTS_QUERY);
if (loading) return <Loading />;
const nodes = data.comments.edges.map((edge) => edge.node);
const pageInfo = data.comments.pageInfo;
return (
<Comments
entries={nodes}
onLoadMore={() => {
if (pageInfo.hasNextPage) {
fetchMore({
variables: {
cursor: pageInfo.endCursor,
},
});
}
}}
/>
);
}
import React from "react";
import { ApolloConsumer, useApolloClient, useQuery, gql } from "@apollo/client";
const GET_MESSAGE_COUNT = gql`
query GetMessageCount {
messageCount @client {
total
}
}
`;
const resolvers = {
Query: {
messageCount: (_, args, { cache }) => {
// ... calculate and return the number of messages in
// the cache ...
return {
total: 123,
__typename: "MessageCount",
};
},
},
};
export function MessageCount() {
const client = useApolloClient();
client.addResolvers(resolvers);
const { loading, data: { messageCount } } = useQuery(GET_MESSAGE_COUNT);
if (loading) return "Loading ...";
return (
<p>
Total number of messages: {messageCount.total}
</p>
);
};
import { gql, useQuery } from '@apollo/client';
const GET_GREETING = gql`
query GetGreeting($language: String!) {
greeting(language: $language) {
message
}
}
`;
function Hello() {
const { loading, error, data } = useQuery(GET_GREETING, {
variables: { language: 'english' },
});
if (loading) return <p>Loading ...</p>;
return <h1>Hello {data.greeting.message}!</h1>;
}
import React from "react";
import { useApolloClient } from "@apollo/client";
import Link from "./Link";
function FilterLink({ filter, children }) {
const client = useApolloClient();
return (
<Link
onClick={() => client.writeQuery({
query: gql`query GetVisibilityFilter { visibilityFilter }`,
data: { visibilityFilter: filter },
})}
>
{children}
</Link>
);
}
import React from 'react';
import ReactDOM from 'react-dom';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from '@apollo/client';
import Pages from './pages';
import Login from './pages/login';
const cache = new InMemoryCache();
const client = new ApolloClient({
uri: 'http://localhost:4000/graphql',
cache
});
const IS_LOGGED_IN = gql`
query IsUserLoggedIn {
isLoggedIn @client
}
`;
cache.writeQuery({
query: IS_LOGGED_IN,
data: {
isLoggedIn: !!localStorage.getItem("token"),
},
});
function App() {
const { data } = useQuery(IS_LOGGED_IN);
return data.isLoggedIn ? <Pages /> : <Login />;
}
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root"),
);