reactjs - 对graphql API的反应调用返回未定义
问题描述
我遇到了 react 和 graphQL API 的问题。我一直在尝试在 API 上运行一个简单的查询,但每次我尝试运行它时,我都无法获得未定义的结果或“错误!JSON 中位置 0 处的意外令牌 <”。这是我的查询代码。
import React, { useEffect, useState } from 'react';
import { useQuery, gql } from '@apollo/client';
import xtype from 'xtypejs';
// import { LOAD_INGREDIENTS } from '../GraphQL/queries';
const LOAD_INGREDIENTS = gql `
query Ingredients{
ingredients{
id
name
}
}
`
function GetIngredients() {
const {error, loading, data} = useQuery(LOAD_INGREDIENTS, { fetchPolicy: 'no-cache' })
const [ingredients, setIngredients] = useState([])
useEffect(() => {
if (data){
console.log(data);
setIngredients(data.getAllIngredients)
}
}, [data]);
// Citation: https://stackoverflow.com/questions/59920824/usequery-returns-undefined-but-returns-data-on-gql-playground
console.log(xtype.type(data)) // returning undefined
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
if (!data) return 'Not found';
return (<div>
{ingredients.map((val) => {
return <p> {val.name} </p>
})}
</div>
);
}
导出默认的GetIngredients;
这是我的客户端代码并调用 API。
import {
ApolloClient, InMemoryCache, ApolloProvider,
HttpLink, from
} from '@apollo/client';
import {onError} from '@apollo/client/link/error';
import GetIngredients from './Components/get_ingredients';
const errorLink = onError(({ graphqlErrors, networkError}) => {
if (graphqlErrors){
//graphqlErrors.map(({message, location, path}) => {
alert('GraphQL error')
// });
}
})
const link = from ([
errorLink,
new HttpLink({ uri: link_to_api}),
]);
const client = new ApolloClient({
cache: new InMemoryCache(),
uri: link,
headers: {
authorization: `Bearer : ${process.env.REACT_APP_PLANTJAMMER_API_KEY}`,
},
});
有人可以帮我理解发生了什么吗?
解决方案
推荐阅读
- php - 您如何创建一个在 php 中过期的缓存(或者更好的是,如果页面内容中的任何内容已更新,则该缓存会刷新)
- python-3.x - 从 bash 脚本内部调用时,Python 列表未排序
- javascript - 如何使用 express 为自定义过滤器配置 nunjucks?
- postgresql - 使用 JSON 字段将转义的双引号插入 Postgres 表
- azure - 使用 Active Directory 进行 Azure 应用服务身份验证
- java - 从 div 类下拉列表中选择 - Selenium 但它不起作用
- reactjs - 一条路线的 CSS 样式和路线不起作用(在屏幕上显示)(它适用于其他路线)
- azure - 在 Azure 经典管道中发布 HTML 文件
- c++ - 使用 CMAKE 将共享库链接到可执行文件
- python - 如何从数据框列的某些行中删除字符?