While I can successfully access my GraphQL query
using apollo-graphql-studio
, and the resolver
is configured correctly, I am facing difficulty in rendering the data.
Being aware of the performance benefits of swr
react-hook
in next-js
, I intend to fetch data using the swr
method:
import useSWR from "swr";
const Query = `
books {
title
}
`;
export default function Home() {
const fetcher = async () => {
const response = await fetch("/api/graphql", {
body: JSON.stringify({ query: Query }),
headers: { "Content-type": "application/json" },
method: "POST"
});
const { data } = await response.json();
return data;
};
const { data, error } = useSWR([Query], fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return (
<div>
<div>hello {data?.books?.title}</div>
</div>
);
}
But currently, it only displays loading...
, indicating that the data is not being fetched correctly. Interestingly, I have no trouble retrieving the data through the Apollo-graphql-studio
IDE
.
The issue seems to lie at the API route /api/graphql
, as indicated by a console error stating 400 Bad Request
.
How can I effectively render the data?
Below is the code for the GraphQL API:
import Cors from 'micro-cors'
import { gql, ApolloServer } from 'apollo-server-micro'
import { Client, Map, Paginate, Documents, Collection, Lambda, Get } from 'faunadb'
const client = new Client({
secret: process.env.FAUNA_SECRET,
domain: "db.fauna.com",
})
export const config = {
api: {
bodyParser: false
}
}
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`
const resolvers = {
Query: {
books: async () => {
const response = await client.query(
Map(
Paginate(Documents(Collection('Book'))),
Lambda((x) => Get(x))
)
)
const books = response.data.map(item => item.data)
return [...books]
},
},
}
const cors = Cors()
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
},
introspection: true,
playground: true,
})
const serversStart = apolloServer.start()
export default cors(async (req, res) => {
if (req.method === "OPTIONS") {
res.end();
return false;
}
await serversStart;
await apolloServer.createHandler({ path: '/api/graphql' })(req, res)
})