next-with-apolloを使ってGraphQLにアクセスする
『初めてのGraphQL』を読み返しながら独自のAPIサーバとクライアントを作っている。
APIサーバの方は、本に載ってたのと同じくapollo-server-expressを使って実装した。
クライアントの方はNext.jsで作っていたので本のやり方そのままはできなかったのでnext-with-apolloを使って実装した。
READMEの手順に沿って、[[lib/withApollo.tsx]]を作成。
// lib/withApollo.tsx
import withApollo from "next-with-apollo";
import ApolloClient, { InMemoryCache } from "apollo-boost";
import { ApolloProvider } from "@apollo/react-hooks";
export default withApollo(
({ initialState }) => {
return new ApolloClient({
uri: process.env.GRAPHQL_URI,
cache: new InMemoryCache().restore(initialState || {}),
fetch
});
},
{
render: ({ Page, props }) => {
return (
<ApolloProvider client={props.apollo}>
<Page {...props} />
</ApolloProvider>
);
}
}
);
withApolloでpageコンポーネントを呼び出せば、GraphQLのレスポンスを取得できるようになる。
// page/items.tsx
import { useRouter } from "next/router";
import * as React from "react";
import gql from "graphql-tag";
import { useQuery } from "@apollo/react-hooks";
import withApollo from "~/lib/withApollo";
const QUERY = gql`
{
allItems {
id
name
}
}
`;
const ItemsPage: React.FunctionComponent = () => {
const router = useRouter();
const { loading, data } = useQuery(QUERY);
if (loading || !data) {
return <h1>loading...</h1>;
}
console.log("data", data);
return (
<div>Items</div>
);
};
export default withApollo(ItemsPage);