queen.raae.codes ยท a developerโ€™s logbook
1 min read

createNode does NOT return anything useful

Written in 2022, 4 years ago. Tools and advice may have moved on since.

createNode does not return anything useful:

// gatsby-node.js

// Should be sourced or derived, only for example purposes
const DATA = { id: "unique", hello: "world" };

exports.sourceNodes = async (gatsbyUtils) => {
  const { actions, createNodeId, createContentDigest } = gatsbyUtils;
  const { createNode } = actions;

  const awaitedNode = await createNode({
    ...DATA,
    id: createNodeId(`example-node-${DATA.id}`),
    internal: {
      type: `BadExample`,
      contentDigest: createContentDigest(DATA),
    },
  });
  console.log(">>>> awaitedNode:", awaitedNode); // ๐Ÿ‘ˆ
  // Console:
  // >>> awaitedNode: []
};

Therefore to create a child-parent link in onCreateNode for instance, you need to keep a reference to the id yourself:

// gatsby-node.js

// Should be sourced or derived, only for example purposes
const DATA = { id: "unique", hello: "world" };

exports.onCreateNode = (gatsbyUtils) => {
  const { node, actions, createNodeId, createContentDigest } = gatsbyUtils;
  const { createNode, createParentChildLink } = actions;

  if (node.internal.type !== "Parent") return;

  const nodeId = createNodeId(`example-node-${DATA.id}`); // ๐Ÿ‘ˆ

  createNode({
    ...DATA,
    id: nodeId, // ๐Ÿ‘ˆ
    internal: {
      type: `Child`,
      contentDigest: createContentDigest(DATA),
    },
  });

  // ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡
  createParentChildLink({ parent: node, child: { id: nodeId } });
};

A more common version of the code above that you see in examples are:

// gatsby-node.js

// Should be sourced or derived, only for example purposes
const DATA = { id: "unique", hello: "world" };

exports.onCreateNode = (gatsbyUtils) => {
  const { node, actions, createNodeId, createContentDigest } = gatsbyUtils;
  const { createNode, createParentChildLink } = actions;

  if (node.internal.type !== "Parent") return;

  const childNode = {
    ...DATA,
    id: createNodeId(`example-node-${DATA.id}`),
    internal: {
      type: `Child`,
      contentDigest: createContentDigest(DATA),
    },
  };

  // ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡
  createNode(childNode);
  createParentChildLink({ parent: node, child: childNode });
};

However, Iโ€™m not too fond of indicating that the data object describing the node is already an actual node in the data layer, so I prefer my initial solution as only the id is needed to create the link.

ย 

All the best,
Queen Raae

Join the crew!

All the shenanigans from me and my piratical family, straight to your inbox.

Search the log

โ†‘โ†“ to move ยท Enter to open ยท Esc to close All entries โ†’