无法使用React.js渲染GraphQl数据

发布于 2025-01-19 17:10:43 字数 4823 浏览 3 评论 0原文

我正在尝试使用 apollo 客户端、服务器、ReactJS 和 NodeJS 显示来自 API 的值,下面是执行此操作的代码:

客户端:

UserPosts.js:

import { useMutation, useQuery } from "@apollo/client";
import { USERPostedImages } from "./query";

function UserPosts() {
  const { loading, error, data } = useQuery(USERPostedImages);
  
 
 
  return (
    <div className="App">
      {data.userPostedImages.map((data) => (
        <>
          <p key={data.posterName}>
            {data.url}----{data.description}
          </p>
          
        </>
      ))}
   
    </div>
  );
}

export default UserPosts;

用于 graphql 查询的 query.js:

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

export const unsplashImages = gql`
  {
    unsplashImages {
      
      url
      posterName
      description

    }
  }
`;

export const USERPostedImages = gql`
  {
    userPostedImages {
      
      url
      posterName
      description

    }
  }
`;

App.js:

import React from 'react';

import {NavLink, BrowserRouter as Router, Route} from 'react-router-dom';
import UserPosts from './components/UserPosts';
import Bin from './components/Bin';
import Home from './components/Home';
import NewPost from './components/NewPost';
import UnsplashPosts from './components/UnsplashPosts';

import {
  ApolloClient,
  HttpLink,
  InMemoryCache,
  ApolloProvider
} from '@apollo/client';
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'http://localhost:4000'
  })
});

function App() {
  return (
    <ApolloProvider client={client}>
      <Router>
        <div>
          <header className='App-header'>
            <h1 className='App-title'>
              GraphQL Lab5
            </h1>
            <nav>
              <NavLink className='navlink' to='/'>
                Home
              </NavLink>
              <NavLink className='navlink' to='/my-bin'>
                Bin
              </NavLink>

              <NavLink className='navlink' to='/my-posts'>
                Posts
              </NavLink>

              <NavLink className='navlink' to='/new-post'>
                Create New Post
              </NavLink>
            </nav>
          </header>
          <Route exact path='/' component={UnsplashPosts} />
          <Route path='/my-bin/' component={Bin} />
          <Route path='/my-posts' component={UserPosts} />
          <Route path='/new-post' component={NewPost} />
        </div>
      </Router>
    </ApolloProvider>
  );
}

export default App;

服务器

index.js:

const {ApolloServer, gql} = require('apollo-server');
const axios = require('axios');
const uuid = require('uuid'); 
const bluebird = require('bluebird'); 
const redis = require('redis')
const client = redis.createClient();

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
   
const typeDefs = gql`
  type Query {
    photos: [Photo]
    post: [ImagePost]
    unsplashImages: [ImagePost]
    userPostedImages: [ImagePost]
  }
  
  type Photo {
    id: String
    username: String
  }

  type ImagePost {
    id: String!
    url: String!
    posterName: String!
    description: String
    userPosted: Boolean
    binned: Boolean
  }

  type Mutation {
    uploadImage(
      url: String!
      description: String
      posterName: String
    ): ImagePost
  }
 
`;


const resolvers = {
  Query: {
    unsplashImages: async (_, args) => {
      const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
      const a =  data.map(imagePost => {
        return {
          id: imagePost.id,
          posterName: imagePost.user.name,
          url: imagePost.urls.raw,
          description: imagePost.description,
        }
      })
      return a;
    },
  userPostedImages: async (_,args) => {
    let history = await client.lrangeAsync("postedImagesList",0,100).map(JSON.parse);
    return history;
  }
},
    Mutation: {
      uploadImage: async (_,args) => {
        //const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
        const newPost = {
          id: uuid.v4(),
          url: args.url,
          description: args.description,
          posterName: args.posterName,
          binned: false,
          userPosted: true,

        }
        await client.lpushAsync("postedImagesList",JSON.stringify(newPost));
      }
    }

};

const server = new ApolloServer({typeDefs, resolvers});

server.listen().then(({url}) => {
  console.log(`
              

I am trying to display values from an API using apollo client, server, ReactJS and NodeJS, Below is the code to do this:

Client:

UserPosts.js:

import { useMutation, useQuery } from "@apollo/client";
import { USERPostedImages } from "./query";

function UserPosts() {
  const { loading, error, data } = useQuery(USERPostedImages);
  
 
 
  return (
    <div className="App">
      {data.userPostedImages.map((data) => (
        <>
          <p key={data.posterName}>
            {data.url}----{data.description}
          </p>
          
        </>
      ))}
   
    </div>
  );
}

export default UserPosts;

query.js for the graphql queries:

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

export const unsplashImages = gql`
  {
    unsplashImages {
      
      url
      posterName
      description

    }
  }
`;

export const USERPostedImages = gql`
  {
    userPostedImages {
      
      url
      posterName
      description

    }
  }
`;

App.js:

import React from 'react';

import {NavLink, BrowserRouter as Router, Route} from 'react-router-dom';
import UserPosts from './components/UserPosts';
import Bin from './components/Bin';
import Home from './components/Home';
import NewPost from './components/NewPost';
import UnsplashPosts from './components/UnsplashPosts';

import {
  ApolloClient,
  HttpLink,
  InMemoryCache,
  ApolloProvider
} from '@apollo/client';
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'http://localhost:4000'
  })
});

function App() {
  return (
    <ApolloProvider client={client}>
      <Router>
        <div>
          <header className='App-header'>
            <h1 className='App-title'>
              GraphQL Lab5
            </h1>
            <nav>
              <NavLink className='navlink' to='/'>
                Home
              </NavLink>
              <NavLink className='navlink' to='/my-bin'>
                Bin
              </NavLink>

              <NavLink className='navlink' to='/my-posts'>
                Posts
              </NavLink>

              <NavLink className='navlink' to='/new-post'>
                Create New Post
              </NavLink>
            </nav>
          </header>
          <Route exact path='/' component={UnsplashPosts} />
          <Route path='/my-bin/' component={Bin} />
          <Route path='/my-posts' component={UserPosts} />
          <Route path='/new-post' component={NewPost} />
        </div>
      </Router>
    </ApolloProvider>
  );
}

export default App;

Server

index.js:

const {ApolloServer, gql} = require('apollo-server');
const axios = require('axios');
const uuid = require('uuid'); 
const bluebird = require('bluebird'); 
const redis = require('redis')
const client = redis.createClient();

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
   
const typeDefs = gql`
  type Query {
    photos: [Photo]
    post: [ImagePost]
    unsplashImages: [ImagePost]
    userPostedImages: [ImagePost]
  }
  
  type Photo {
    id: String
    username: String
  }

  type ImagePost {
    id: String!
    url: String!
    posterName: String!
    description: String
    userPosted: Boolean
    binned: Boolean
  }

  type Mutation {
    uploadImage(
      url: String!
      description: String
      posterName: String
    ): ImagePost
  }
 
`;


const resolvers = {
  Query: {
    unsplashImages: async (_, args) => {
      const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
      const a =  data.map(imagePost => {
        return {
          id: imagePost.id,
          posterName: imagePost.user.name,
          url: imagePost.urls.raw,
          description: imagePost.description,
        }
      })
      return a;
    },
  userPostedImages: async (_,args) => {
    let history = await client.lrangeAsync("postedImagesList",0,100).map(JSON.parse);
    return history;
  }
},
    Mutation: {
      uploadImage: async (_,args) => {
        //const { data } = await axios.get('https://api.unsplash.com/photos/?client_id=2zceQd7D4SraKoqW_GjPzXboSup3TKRIPk7EXfJBcAs');
        const newPost = {
          id: uuid.v4(),
          url: args.url,
          description: args.description,
          posterName: args.posterName,
          binned: false,
          userPosted: true,

        }
        await client.lpushAsync("postedImagesList",JSON.stringify(newPost));
      }
    }

};

const server = new ApolloServer({typeDefs, resolvers});

server.listen().then(({url}) => {
  console.log(`????  Server ready at ${url} ????`);
});

When I run my client I get the below error:

Uncaught TypeError: Cannot read properties of undefined (reading 'userPostedImages')
    at UserPosts (UserPosts.js:22:1)

I am not sure what I am doing wrong, my server is working fine and am able to see data in graphql playground but nothing shows up on the client.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埖埖迣鎅 2025-01-26 17:10:43

数据尚无可用(null),因为它仍在获取,因此要处理此问题,请使用加载值的条件渲染。

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

if(error) {
 return <h1> error</h1>;
}

if(loading) {
 return <h1> loading</h1>;
}

....

data is not available (null) yet because it is still fetching, so to handle this, use conditional rendering with loading value.

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

if(error) {
 return <h1> error</h1>;
}

if(loading) {
 return <h1> loading</h1>;
}

....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文