Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing argument to react-apollo-hooks useQuery

How can I pass an argument to useQuery when using react-apollo-hook?

This does not work:

  const { data, loading, error } = useQuery(GET_DATA,
{ variables: { id: 'testId' }});

And the query itself:

export const GET_DATA = gql`
{ query ($id: String) {
  document(id: $uid) {
    uid
  }  
 }
}
`;
like image 728
Murakami Avatar asked May 20 '19 15:05

Murakami


People also ask

How do you use useQuery in React?

We run a query within a React component by calling useQuery and passing it our GraphQL query string. This makes running queries from React components a breeze. When our component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties that we can use to render our UI.

What is useQuery in Apollo?

The useQuery React hook is the primary API for executing queries in an Apollo application. To run a query within a React component, call useQuery and pass it a GraphQL query string.

How do you pass variables in GraphQL query React?

It uses React's render props pattern. import React from "react"; import { Query } from "react-apollo"; import gql from "graphql-tag"; const GET_TODOS = gql` { todos { id type } } `; const Todos = () => ( <Query query={GET_TODOS}> {({ loading, error, data }) => { if (loading) return <p>Loading...

What is the correct syntax of using the useMutation hook in React?

import { useMutation } from "@apollo/client"; We are importing the useMutation React hook from @apollo/client and the graphql query we defined above to fetch the todo data. }; In the useMutation React hook defined above, the first argument of the result tuple is the mutate function; (addTodo) in this case.


1 Answers

Your query is not valid because 1) it's wrapped in an extraneous pair of curly brackets and 2) you reference a variable named uid, while the variable you defined is actually called id. Corrected, this query would look like:

query ($id: String) {
  document(id: $id) {
    uid
  }
}

Keep in mind, I don't know what your actual schema is so this query could still be invalid if any of the fields or arguments do not exist or are of the wrong type.

like image 105
Daniel Rearden Avatar answered Nov 03 '22 04:11

Daniel Rearden