首页 > 解决方案 > 对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}`,
  },
});

有人可以帮我理解发生了什么吗?

标签: reactjsgraphqlapollo-client

解决方案


推荐阅读