What is the process for utilizing SWR to display information from a GraphQL Apollo Server within a NextJS application?

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)
})

Answer â„–1

I like to use Apollo Client in this way:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const defaultOptions: any = {
  watchQuery: {
    fetchPolicy: "no-cache",
    errorPolicy: "ignore",
  },
  query: {
    fetchPolicy: "no-cache",
    errorPolicy: "all",
  },
};

const cache = new InMemoryCache({
  resultCaching: false,
});


const link = createHttpLink({
  uri: process.env.NEXT_PUBLIC_GRAPQL_URI,
  
});

export const client: any = new ApolloClient({
 
  connectToDevTools: true,
  link,
  cache,
  defaultOptions,
});

Next, in the frontend:

const { data, error } = useSWR(MY_QUERY, query => client.query({ query }));

A similar setup applies to Apollo Server as well

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conceal a table row (tr) from a data table following deletion using ajax in the CodeIgniter

I am attempting to remove a record in codeigniter using an ajax call. The delete function is functioning correctly, but I am having trouble hiding the row after deletion. I am utilizing bootstrap data table in my view. <script> function remove_car ...

A guide on accessing header response information in Vue.js

Currently, I am operating on my localhost and have submitted a form to a remote URL. The process unfolds in the following sequence: Submission of a form from localhost Being redirected to a remote URL Sending a response back from the Remote URL to localh ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

What is the best approach for manipulating live data in localStorage using ReactJS?

I am working on creating a page that dynamically renders data from localStorage in real-time. My goal is to have the UI update instantly when I delete data from localStorage. Currently, my code does not reflect changes in real-time; I have to manually rel ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

What steps should I take to address the issues with my quiz project?

I've been working on a new project that involves creating a quiz game. I came across some code online and decided to customize it for my needs. However, I'm encountering some issues with the functionality of the game. Right now, the questions ar ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

The backtick is not functioning correctly when trying to append the result in the Internet Explorer browser

I am using the .html method to append HTML content to a specific div ID within my file. <html> <head> Title <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> ...

Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap. My goal is to save a .aspx page as an HTML file within my application. Upon writing the code: using System; using System.Collections.Generic; using System.Linq; using S ...

Toggle the visibility of an element by clicking a button

I have a table structured as follows: <tr> <td class="title">Title</td> <td class="body">Body</td> <td class="any">Any text</td> </tr> <tr> <td class="title">Title</td> ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

Can pagination numbers in Jquery DataTable be configured based on the total records returned by the server and the number of records chosen by the user?

I am currently diving into the world of DataTable.js, a jQuery plugin, and working hard to articulate my questions effectively. For my specific needs, I need to retrieve only 10 records initially whenever an AJAX request is made, even if there are 100 rec ...

What could be causing my input to not activate my function?

I am having issues with my input buttons not triggering my functions. Can anyone provide some insight into this problem? <div id="windowBar"> <h3>Imagine you were a superhero...</h3> <input id="WindowClose" type="button" onclick=" ...

Error Message: An issue has occurred with the server. The resolver function is not working properly in conjunction with the next

https://i.stack.imgur.com/9vt70.jpg Encountering an error when trying to access my login page. Using the t3 stack with next auth and here is my [...nextauth].ts file export const authOptions: NextAuthOptions = { // Include user.id on session callbacks ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Issue: Cannot access the 'map' property of an undefined value in a React Mongo DB error

My React code was running perfectly fine until I encountered an error message in the browser console: "TypeError: Cannot read property 'map' of undefined". Let me share the snippet of my code with you. const MyComponent = () => { const [dat ...

Tips for displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...