如何正确将变量传递给apollo useQuery?

时间:2019-10-20 21:33:44

标签: graphql apollo react-apollo apollo-client

所以我需要一双新鲜的眼睛来帮助我!我刚刚开始为阿波罗使用新的挂钩,它们非常酷!但是,当我尝试传递变量时遇到了一个问题,它返回未定义的值。

我在graphql服务器中有一个查询,该服务器命中了一个rest API,但目前我只返回标量JSON

fetchRecipes(calories: String!, meal: String!): JSON

在我的组件中:

  const { data, loading, error } = useQuery(FETCH_RECIPES, {
    variables: { calories: 500, meal: "beef" }
  });
const FETCH_RECIPES = gql`
  query FetchRecipes($calories: String, $meal: String) {
    fetchRecipes(calories: $calories, meal: $meal)
  }
`;

当我console.log(data)返回undefined时,

但是,为什么这样做呢? (不通过useQuery传递变量)

  query {
    fetchRecipes(calories: "500", meal: "beef")
  }

这是组件的外观:

const Recipes = () => {
  const { data, loading, error } = useQuery(FETCH_RECIPES, {
    variables: { calories: "500", meal: "beef" }
  });

  if (loading) return <Loading>Loading...</Loading>;
  if (error) return <Error>Data couldn't be fetched</Error>;

  return (
    <RecipeContext.Consumer>
      {({ suggestedCaloricIntake }) => (
        <View>
          <Text>Suggested: {suggestedCaloricIntake}</Text>

          <Picture
            style={{ width: 150, height: 150 }}
            source={{ uri: data.fetchRecipes.hits[0].recipe.image }}
            accessibilityLabel='meal image'
          />
        </View>
      )}
    </RecipeContext.Consumer>
  );
};

1 个答案:

答案 0 :(得分:0)

我认为问题在于您将calories: 500作为整数输入到查询中,但是您用calories: String!告诉您,您仅接受{{1}的 String }

编辑: 如果API接受,请删除!,否则将输入Value更改为“ 500” 例如

!