0

So I am trying to pull in some data from Hygraph in a new Next JS application, I recieve the error of Error: Cannot read properties of undefined (reading 'map').

I am new to both these technologies and cannot find a solutions, for reference I create a new Next JS application and imported graphql and graphql-request and the following code is inside the page.js file inside the app folder.

import styles from './page.module.css'
import { GraphQLClient, gql } from 'graphql-request'

const graphcms = new GraphQLClient(
  "https://api-eu-west-2.hygraph.com/v2/xxxxxxxxxxxxxx/master"
);

const QUERY = gql`
{
  articles {
    createdAt
    id
    publishedAt
    released
    slug
    title
    updatedAt
    coverPhoto {
      url
    }
    content {
      html
    }
  }
}
`;

export async function getStaticProps(){
  const {articles} = await graphcms.request(QUERY);
  return {
    props: {
      articles,
    },
    revalidate: 10,
  }
}

export default function Home({articles}) {
  return (
    <main className={styles.main}>
      {articles.map((article) => (
        <h1>{article.title}</h1>
      ))}
    </main>
  )
}

Any help on this issue would be much appreciated.

Screen shot showing error is here: Error picture

Updated error output: New Error Picture

Lewis
  • 1
  • 5
  • I think the articles are returned in a "data" key. Can you try changing the line `const {articles} = await graphcms.request(QUERY)` to `const {data} = await graphcms.request(QUERY)` And also change `props: { articles,}` to `props: { articles: data.articles}`, – Stem Florin May 27 '23 at 13:29
  • @StemFlorin Just tried this and the same issue is still coming through, have added a screen shot to the original post to show error also, if that helps. – Lewis May 27 '23 at 19:38
  • OH I just notice you are also doing destructuring in the component. Then update your code to : `props: { articles: data}`. – Stem Florin May 28 '23 at 08:16
  • @StemFlorin I have updated the component as you have said but the issue persists. – Lewis May 28 '23 at 08:23
  • can you edit your question and add the response you get from the endpoint? – Stem Florin May 28 '23 at 08:28
  • Updated error output has been added to the end of question, hope this helps – Lewis May 28 '23 at 13:36

1 Answers1

0

You need to create a token in your hygraph, its on the same page where your api is. Make sure to add all permissions. Then your code should look like that instead:

const graphcms = new GraphQLClient(YOUR_API_LINK, {
headers: {
  Authorization: "Bearer YOUR_TOKEN_VALUE", //make sure your token and Bearer have a space between them
},});

Hope this helps

  • Hi, I added this in but I'm afraid the issue persists. The error is as follows: Error: Cannot read properties of undefined (reading 'map') – Lewis Jun 22 '23 at 19:36