I am using gatsby with wordpress to display events from the events calendar API of wordpress . I am using the plugin gatsby-source-tribe-events
to access the allTribeEvents
graphql field . The problem is that if I have no events posted on wordpress the field allTribeEvents
is not created and then if I run my graphql query on gatsby I get
Cannot query field "allTribeEvents" on type "Query"
So my problem is how to check if the field exists in graphql and query conditionally based on it .
My code :
React component to display events :
export default function Events() {
const data = useStaticQuery(graphql`
query EventsQuery {
allTribeEvents {
...
}
}`);
//then I return my component based on the data
}
So the point is that if no posts exist "allTribeEvents"
is not created in grapqhl and I get an error
CodePudding user response:
So my problem is how to check if the field exists in graphql and query conditionally based on it .
Short answer, you can't. Essentially because when you query something, you expect some result. The problem here is that because of the defined worfklow (WordPress -> Gatsby -> GraphQL node creation), the steps are broken.
The ideal solution in this cases, is to define a Custom GraphQL Schema Definition that will help you to tell Gatsby that the allTribeEvents
can be null
.
Another possible workaround (far less clean) is to create an empty tribe event (maybe with empty spaces or with some kind of defined field) and treat it in the front-end to avoid printing it (let's say you have an event named "-", if you find that field in the GraphQL query, filter it).