Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
How can I use SWR to render data from an Apollo Server instance of GraphQL, in a NextJS app?

I can successfully view my GraphQL query via apollo-graphql-studio: The resolver is correctly configured, but I'm not sure how to render data.

I know that the next-js swr react-hook is performant, so I'd like to fetch data via 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>
  );
}

This is just returning loading... so the data is clearly not correctly fetched. Although, as I said, I can retrieve it via the Apollo-graphql-studio IDE.

The console error is a 400 Bad Request on the API route: /api/graphql, so this is where the problem is.

How can I render the data?

Here's 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)
})
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda