Add a schema to avoid GraphQL cannot query errors  🧱 🗂

In yesterday's email, we solved the

Cannot query field "allUserAvatar" on type "Query"

issue by stopping the build if no data is sourced.

However, you often want to allow empty data queries. Maybe the blog posts are not written yet, or there are no images for the gallery yet.

In that case, defining the expected schema will help.

// File: gatsby-node.js

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
  const typeDefs = `
    type UserAvatar implements Node {
      username: String!
      avatarUrl: String!
    }
  `;
  createTypes(typeDefs);
};

The GraphQL queries will longer fail 💪

When choosing this solution, you should remember to account for missing data in your components. It could be as simple as returning nothing when no data is available:

if (data.allUserAvatar.nodes.length === 0) return null;

See the code changes made to Prune your follows on Github to allow for empty avatar data.

 

All the best,
Queen Raae

 

PS: I spy with my little eye something beginning with 5...and ends in alpha...

Stuck on a reef in the sharky waters around the Gatsby islands?

Book a 1-on-1 Gatsby Call with Queen Raae. Friendly advice you can put into action immediately, guaranteed!

Serious about Gatsby? Sign up for emails sent every weekday to help you get the most out of Gatsby!