为什么我的 React 应用程序没有映射我的 graphQL 查询?

问题描述 投票:0回答:1

我正在开发一个组件,使用语义 UI 在客户端映射来自 graphQL 查询的所有帖子。我在本地运行它,即使此查询在 apollo studio 中工作,网页也没有显示任何数据。

这是该组件的代码。

import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../utils/queries';

export const PostFeed = () => {
    const { loading, data } = useQuery(GET_POSTS, {
        fetchPolicy: "no-cache"
    });
    const posts = data?.post || [];

    return (
        <div>
            <h1>Post feed</h1>
            {loading ? (
                <div>Loading...</div>
            ) : (
                <div className="ui feed">
                {posts.map((post) => {
                    return (
                    <div className="event post">
                        <div className="label">
                            {/* <img src={post.author.profilePic}/> */}
                        </div>
                        <div className="content">
                            <div className="summary">
                                <a className="user">
                                    {post.postAuthor}
                                </a>posted on their page
                                <div className="date">
                                    {/* {post.createdAt} */}
                                </div>
                            </div>
                            <div className="extra text">
                                {post.postText}
                            </div>
                            <div className="meta">
                                <a className="like">
                                    {/* <i className="like icon"></i>{post.likes} */}
                                </a>
                            </div>
                        </div>
                    </div>
                    );
                })}
             </div>
            )}
        </div>
    )
}

这是实用程序/查询代码:

import { gql } from '@apollo/client';

export const GET_POSTS = gql`
query GetPosts {
  getPosts {
    _id
    postAuthor
    postText
  }
}
`;

我编写了以下代码以确保查询正在提取数据并且它确实返回正确的数据点(在屏幕截图中共享)。

  const { loading, error, data } = useQuery(GET_POSTS);

  if (loading) return "Loading...";
  
  if (error) return `Error! ${error.message}`;
  
  return (<div>{JSON.stringify(data)}</div>);

stringify data

所以问题似乎出在映射函数或语义 UI 上。该页面在消失之前会短暂显示 Loading div。semantic ui

reactjs react-hooks graphql apollo semantic-ui
1个回答
0
投票

当您应该指

data.post
时,您指的是
data.getPosts

尝试:

const posts = data?.getPosts || [];
© www.soinside.com 2019 - 2024. All rights reserved.