Reactjs 对graphql API的React调用返回未定义的
我对react和GraphQLAPI有问题。我一直在尝试在API上运行一个简单的查询,但每次尝试运行它时,我都无法找到未定义的结果或“Error!Unexpected token<在JSON中的位置0”。这是我的查询代码Reactjs 对graphql API的React调用返回未定义的,reactjs,graphql,apollo-client,Reactjs,Graphql,Apollo Client,我对react和GraphQLAPI有问题。我一直在尝试在API上运行一个简单的查询,但每次尝试运行它时,我都无法找到未定义的结果或“Error!Unexpected token
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>
);
}
有人能帮我理解发生了什么事吗
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}`,
},
});