aromanarguello
aromanarguello

Reputation: 766

How to properly pass variables to apollo useQuery?

So I need a pair of fresh eyes to help me out! I just started using the new hooks for apollo and they are pretty cool! However, I am running into an issue when I try to pass variables, it returns undefined.

I have this query in a graphql server which hits a rest API but at the moment I just have returning scalar JSON

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

in my component:

  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)
  }
`;

when I console.log(data) it returns undefined,

however, why does this work? (not passing the variables through useQuery)

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

This is what the component looks like:

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>
  );
};

Upvotes: 8

Views: 16360

Answers (1)

louisrtz
louisrtz

Reputation: 172

I think the issue is that you give calories: 500 as an integer into the query but you told with calories: String! that you only accept a String with the !

EDIT: Remove the ! if the API accept it, otherwise change the input Value to "500" e.g

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

Upvotes: 6

Related Questions