无法使用react.js呈现graphql数据



我正在尝试使用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(`🚀  Server ready at ${url} 🚀`);
});

当我运行我的客户端时,我得到以下错误:

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

我不确定我做错了什么,我的服务器运行良好,能够在graphql操场上看到数据,但客户端上什么都没有显示。

data还不可用(null(,因为它仍在获取,所以要处理此问题,请使用具有loading值的条件渲染。

const { loading, error, data } = useQuery(USERPostedImages);
if(error) {
return <h1> error</h1>;
}
if(loading) {
return <h1> loading</h1>;
}
....

最新更新