I have my project setup to import .graphql
files. That works fine. But my problem is I don't know how to define a query in a .graphql
file and import that into a component to use with react-apollo
's <Query ...>
component.
In this example the author defines the query in JavaScript variable using gql
:
import gql from "graphql-tag";
import { Query } from "react-apollo";
const GET_DOGS = gql`
{
dogs {
id
breed
}
}
`;
const Dogs = ({ onDogSelected }) => (
<Query query={GET_DOGS}>
{({ loading, error, data }) => {
if (loading) return "Loading...";
if (error) return `Error! ${error.message}`;
return (
<select name="dog" onChange={onDogSelected}>
{data.dogs.map(dog => (
<option key={dog.id} value={dog.breed}>
{dog.breed}
</option>
))}
</select>
);
}}
</Query>
);
But, I instead want to store that query in a separate .graphql
file and import it into the component.
Here's what I have tried in my project. Here is a component, and I attempt to import UserQuery
from my schema.
import React from 'react'
import { Query } from 'react-apollo'
import { UserQuery } from '../api/schema.graphql'
export default () =>
<Query query={ UserQuery }>
{({ loading, error, data }) => {
if (loading) return 'Loading...'
if (error) return `Error! ${error.message}`
return
<ul>
{data.users.map(name => <li>{name}</li>)}
</ul>
}}
</Query>
Here is the schema
:
# schema.graphql
query UserQuery {
user {
name,
age,
gender
}
}
type User {
name: String,
age: Int,
gender: String
}
type Query {
say: String,
users: [User]!
}
When I try to import and use I get an error:
modules.js?hash=e9c17311fe52dd0e0eccf0d792c40c73a832db48:28441 Warning: Failed prop type: The prop
query
is marked as required inQuery
, but its value isundefined
.
How can I import queries this way?