Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information.


import { useQuery } from "@apollo/client";
import { useRouter } from "next/router";
import React from "react";
import Post from "../../../components/Post";
import { GET_POST_LIST_BY_TITLE } from "../../../graphql/queries";

const PostPage = () => {
  const router = useRouter();

  const { data, error } = useQuery(GET_POST_LIST_BY_TITLE, {
    variables: {
      id: router.query.id as string,
    },
  });

  if (error) {
    return <div>Error! {error.message}</div>;
  }

  const post: Post = data?.getPostListByPostTitle;

  console.log(data);
  
  return (
    <div>
      <Post post={post} />
    </div>
  );
};

export default PostPage;
    getPostListByPostTitle(title: String!): [Post]
    @dbquery(
      type: "postgresql"
      query: """
      select * from "post" where title = $1
      """
      configuration: "postgresql_config"
    )

gql query

export const GET_POST_LIST_BY_TITLE = gql`
  query a($title: String!) {
    getPostListByPostTitle(title: $title) {
      id
      title
      username
      body
      created_at
      image
      subreddit {
        created_at
        id
        topic
      }
      subreddit_id
      comments {
        created_at
        id
        text
      }
      votes {
        created_at
        upvote
        username
        post_id
        id
      }
    }
  }
`;

Error! Variable '$title' of required type 'String!' was not provided.

Upon further investigation, I found that the console log output is showing undefined.

Despite my attempts at implementing server-side rendering, I have been unable to resolve this issue so far.

Answer №1

An error has occurred because the id variable is undefined. To resolve this issue, ensure that router.query.id is defined on your page. You can prevent query execution if it's not defined in order to avoid the error:

const { data, error } = useQuery(GET_POST_LIST_BY_TITLE, {
  skip: !router.query.id,
  variables: {
    id: router.query.id as string,
  },
});

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

"Extending Material-UI: Utilizing Multiple Snackbar Components

I've been struggling to display multiple warnings using Snackbar from the Material UI library in my React project. I haven't found any examples with React, only Vue. Can anyone help me with this? Here is the code that I have tried so far: https: ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...

Steps for changing the language in KeyboardDatePicker material ui

Currently, I am utilizing material ui on my website and leveraging the KeyboardDatePicker API with successful results. The only issue is that the months' names and button text are displayed in English, whereas I would prefer them to be in Spanish. Des ...

Why does React redirect me to the main page after refreshing the page, even though the user is authenticated in a private route?

In the process of developing a private route component that restricts unauthenticated users and redirects them to the homepage, we encountered an issue upon page refresh. The problem arises when the current user variable momentarily becomes null after a ...

Building an interactive table

I need help creating a table with dynamic data that can be reused. While the headers are showing up as expected, the rows are not displaying at all. Below is the sample data: [ { "id": "1231", "name": "Michael", "phone": "1122 ...

Challenge with dynamic parent routes

In my React application, different routes are loaded through various parent URLs. For example: {["/sat/", "/act/", "/gre/", "/gmat/", "/toefl/"].map((path) => ( <Route key={path} path={path ...

What is the best way to limit the width of the main component in the Material UI Drawer component?

I am facing an issue with implementing a Drawer in Material UI. My goal is to have the main div's width dynamically adjust to occupy the remaining space in the viewport after the Drawer has taken its share of space. In my component, I have attempted ...

Methods to validate CSS attributes specified within a class using React testing library

I am struggling to validate the CSS properties defined within a class in CSS using the React Testing Library. Unfortunately, I am facing challenges in doing so. Here are the simplified code snippets: import React from "react"; import { render, ...

Error: 'process' is not defined in this TypeScript environment

Encountering a typescript error while setting up a new project with express+ typescript - unable to find the name 'process'https://i.stack.imgur.com/gyIq0.png package.json "dependencies": { "express": "^4.16.4", "nodemon": "^1.18.7", ...

What's the trick to ensuring that state is set with useEffect() every time the page is refreshed?

Hey there! I've got some code that's pretty straightforward and not too complicated, so please take a moment to read through it. (I'm using React with Next.js) First off, in the root file app.js, there's a useEffect function that fetch ...

"Proceeding without waiting for resolution from a Promise's `.then`

I am currently integrating Google Identity Services for login on my website. I am facing an issue where the .then function is being executed before the Promise returned by the async function is resolved. I have temporarily used setTimeout to manage this, b ...

Issue with Circular Progress not reflecting Material-UI-next Theme

After following the documentation, I updated my theme but the circular progress element still displays the default primary color instead of the one specified in the theme. My goal is to enable end users to adjust the theme using mobx computed values, but e ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

An individual page application built with Next.js and React requires unique URLs for every item

I recently created a single-page application using Next JS, React JS, and Tailwind CSS to load various items from Firebase. One of the challenges I am facing is allowing users to reference a specific item from the URL and easily share it with others ...

The Next.js development was hindered by a webpack issue causing the build to

Whenever I try to build my next.js app using npm run build, npm fails and crashes while trying to access the logo.png file from the public directory. This directory is where all static assets like images and icons are stored, so I'm unsure why this er ...

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...