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

aro*_*llo 8 apollo graphql react-apollo apollo-client

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

我在 graphql 服务器中有这个查询,它点击了 REST API,但目前我只返回标量 JSON

fetchRecipes(calories: String!, meal: String!): JSON
Run Code Online (Sandbox Code Playgroud)

在我的组件中:

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

当我console.log(data)它回来时undefined

然而,为什么这会起作用呢?(不通过 传递变量useQuery

  query {
    fetchRecipes(calories: "500", meal: "beef")
  }
Run Code Online (Sandbox Code Playgroud)

该组件如下所示:

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>
  );
};
Run Code Online (Sandbox Code Playgroud)

lou*_*rtz 6

我认为问题是你calories: 500在查询中给出了一个整数,但你告诉calories: String!你只接受一个字符串!

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

const { data, loading, error } = useQuery(FETCH_RECIPES, {
    variables: { calories: "500", meal: "beef" }
  });
Run Code Online (Sandbox Code Playgroud)