【问题标题】:why does my graphql return an empty array?为什么我的 graphql 返回一个空数组?
【发布时间】:2022-01-09 07:41:30
【问题描述】:

我是 graphql 的新手。我有一个前端项目(nextjs)和后端(strapi)。

这是我的代码

import { ApolloClient, InMemoryCache, gql } from '@apollo/client'

export default function Blog({ posts }) {
  console.log('posts', posts)
  return (
    <div>
      {posts.map(post => {
        return (
          <div>
            <p>{posts.heading}</p>
          </div>
        )
      })}
    </div>
  )
}

export async function getStaticProps() {
  const client = new ApolloClient({
    url: 'http://localhost:1337/graphql/',
    cache: new InMemoryCache(),
  })

  const { data } = await client.query({
    query: gql`
      query {
        posts {
          data {
            attributes {
              heading
            }
          }
        }
      }
    `,
  })

  return {
    props: {
      posts: data.posts,
    },
  }
}

除此之外,我还收到此消息“无法解构中间值的属性”。有谁知道为什么,我确定代码是正确的。

【问题讨论】:

  • const response = await client.query ... 记录响应,稍后解构...使用邮递员/游乐场测试查询?
  • 你能给我一个工作的例子吗?

标签: graphql next.js apollo-client strapi graphql-js


【解决方案1】:

首先,我建议在根目录中创建一个文件夹并放置所有 graphql 代码,并且您还会遇到语法错误: 让我举一个例子: /index.js

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

const client = new ApolloClient({
  uri: API,
  cache: new InMemoryCache(),
  defaultOptions: {
    query: {
      fetchPolicy: "network-only",
    },
  },
});

//get category ids
const getCatIds = async () => {
  try {
    const { data } = await client.query({
      query: gql`
        query categoriesId {
          categories(sort: "id:ASC") {
            id
            name
          }
        }
      `,
    });
    return data.categories;
  } catch {
    console.log("error appolo");
  }
};
export {getCatIds}

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 2015-05-25
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2020-08-30
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多