如何从对象中提取数据到Apollo查询组件

时间:2019-05-05 21:43:45

标签: reactjs graphql apollo apollo-client apollo-server

尝试从graphql API提取数据,并且不能使用map(),因为数据是作为对象返回的。
我在Apollo服务器(基于我的架构)上得到了预期的结果。

这是执行代码后得到的:
data.getRandomMeal.map is not a function

在调试时,显示data = { getRandomMeal {...} }

<Query
  query={
    gql`{
      getRandomMeal {
        idMeal
        strMeal
      }
    }`
  }
>
  {({ data }) => { 
    if (data === undefined) return null; 
    return (
      <ul>
        {data.getRandomMeal && data.getRandomMeal.map(meal => (
          <li key={meal.idMeal}>{meal.strMeal} </li>
        ))}
      </ul>
    );
  }}
</Query>
const typeDefs = gql`
  type Meal{
    idMeal: ID
    strMeal: String
    strTags: String
    strCategory: String
  }

  type Query {
    getRandomMeal: Meal
  }
`;

const resolvers = {
  Query: {
    getRandomMeal: async (_, __, { dataSources }) =>
      dataSources.RandomRecipe.getRandomMeal()
  }
};

数据源:

class RandomRecipe extends RESTDataSource{
  constructor() {
    super();
    this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php'; 
  }

  async getRandomMeal(){
    const meal = await this.get('/');
    return meal.meals[0];
  }
};

module.exports = RandomRecipe;

1 个答案:

答案 0 :(得分:0)

const meal = await this.get('/');

有关

this.baseURL = 'https://www.themealdb.com/api/json/v1/1/random.php';

URL错误的结果

'https://www.themealdb.com/api/json/v1/1/random.php/'

中使用空字符串就足够了

const meal = await this.get('');

响应可以直接使用,而无需使用地图:

    {({ data })  => {

      if (data === undefined) return null; 
      const meal = data.getRandomMeal;

      return (
        <ul>
          {meal && (
            <li key={meal.idMeal}>{meal.strMeal} </li>
          )}
        </ul>
      );
    }}
相关问题