question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to add fieldData to created node

See original GitHub issue

Summary

How to add fieldData to already created node?

https://github.com/LekoArts/gatsby-themes/blob/1be7b53e4ab5b466478de4118c4b62eeb47af4f8/themes/gatsby-theme-minimal-blog-core/gatsby-node.js#L242-L258

Above code shows new node for MdxPage is created. There the field data is title and slug. I want to add more field data there for e.g.

const fieldData = {
      title: node.frontmatter.title,
      slug: node.frontmatter.slug,
      other_data: node.frontmatter.other_data,
    }

How can I achieve this? I searched a lot about Gatsby Node API but did not get perfect solution

My attempt

In my project’s gatsby-node.js I tried creating new nodes and I got the solution but it is not perfect and very long reduntant I think

Here other_data is title_2 and I created a new node MdxPage23


  createTypes(`
    interface Page @nodeInterface {
      id: ID!
      slug: String!
      title: String!
      excerpt(pruneLength: Int = 160): String!
      body: String!
    }

    interface Page2 @nodeInterface {
      id: ID!
      slug: String!
      title: String!
      title_2: String!
      excerpt(pruneLength: Int = 160): String!
      body: String!
    }

    type MdxPage implements Node & Page2 {
      slug: String!
      title: String!
      title_2: String!
      excerpt(pruneLength: Int = 140): String! @mdxpassthrough(fieldName: "excerpt")
      body: String! @mdxpassthrough(fieldName: "body")
    }
  `);
};



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

  const { postsPath, pagesPath } = withDefaults(themeOptions);

  // Make sure that it's an MDX node
  if (node.internal.type !== `Mdx`) {
    return;
  }

  // Create a source field
  // And grab the sourceInstanceName to differentiate the different sources
  // In this case "postsPath" and "pagesPath"
  const fileNode = getNode(node.parent);
  const source = fileNode.sourceInstanceName;


  // Check for "pages" and create the "Page" type
  if (node.internal.type === `Mdx` && source === pagesPath) {
    const fieldData = {
      title: node.frontmatter.title,
      title_2: node.frontmatter.title_2,
      slug: node.frontmatter.slug,
    };

    const mdxPageId = createNodeId(`${node.id} >>> MdxPage22`);

    createNode({
      ...fieldData,
      // Required fields
      id: mdxPageId,
      parent: node.id,
      children: [],
      internal: {
        type: `MdxPage33`,
        contentDigest: createContentDigest(fieldData),
        content: JSON.stringify(fieldData),
        description: `Mdx implementation of the Page interface`,
      },
    });

    const node_h = getNode(mdxPageId);

    createParentChildLink({ parent: node, child: getNode(mdxPageId) });
  }
};

Relevant information

Theme

minimal-blog theme (https://minimal-blog.lekoarts.de/)

Environment (if relevant)

  System:
    OS: Linux 4.15 Ubuntu 18 
    Shell: 4.4.20 - /bin/bash
  Binaries:
    Node: 11.14.0 - ~/.nvm/versions/node/v11.14.0/bin/node
    Yarn: 1.21.1 - /usr/bin/yarn
    npm: 6.14.4 - ~/.nvm/versions/node/v11.14.0/bin/npm
  Languages:
    Python: 2.7.17 - /usr/bin/python
  Browsers:
    Chrome: 81.0.4044.129
    Firefox: 75.0
  npmPackages:
    gatsby: ^2.13.3 => 2.20.22
    gatsby-plugin-google-analytics: ^2.1.4 => 2.2.2
    gatsby-plugin-manifest: ^2.2.3 => 2.3.3
    gatsby-plugin-netlify: ^2.1.3 => 2.2.1
    gatsby-plugin-offline: ^2.2.4 => 2.2.10
    gatsby-plugin-sitemap: ^2.2.19 => 2.3.2
    gatsby-plugin-webpack-bundle-analyser-v2: ^1.1.8 => 1.1.8
  npmGlobalPackages:
    gatsby-cli: 2.12.0

File contents (if changed)

gatsby-config.js: N/A package.json: N/A gatsby-node.js: Yes. provided above gatsby-browser.js: N/A gatsby-ssr.js: N/A

Feel free to ask more info if needed

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
LekoArtscommented, May 2, 2020

Hi, thanks for the issue!

In practice this is easy to achieve but I can totally understand that this isn’t straightforward, so no worries 😃

I cloned https://github.com/LekoArts/gatsby-starter-minimal-blog and added a subtitle to the frontmatter of about.mdx inside content/pages/about:

---
title: About
slug: "/about"
subtitle: "The subtitle goes here"
---

For the Page type these lines are important:

https://github.com/LekoArts/gatsby-themes/blob/6b5f08a040dbe196697d187367163f11558a43fa/themes/gatsby-theme-minimal-blog-core/gatsby-node.js#L243-L259

What they say in easier terms (top to bottom):

  • Create a unique node id (a node is the smallest unit of Gatsby’s data store and needs to be unique) with a string that contains the node.id from Mdx (so it’s not the same but if node.id changes also this newly created one changes. Mdx is created with gatsby-plugin-mdx
  • Create a new node (with createNode) that takes in the field data from Mdx and spreads them into the root level (that’s why you can query e.g. the title at the root and not frontmatter.title). Name this node with the type MdxPage
  • Create a Parent => Child relationship link between the new MdxPage node and the parent Mdx node
  • As in the schema customization step it says type MdxPage implements Node & Page the MdxPage is now also accessible under Page

In practice this means:

image

As the MdxPage implements the Page you can directly query the union ... on MdxPage. This more specific type also has access to the parent Mdx. This contains the new frontmatter I added. This works because Gatsby automatically infers this field.

Then you’ll need to shadow the file that contains the query of Page and the component itself. Important: You need to use the .tsx extension (you don’t have to write TypeScript).

You can see the changes here: https://github.com/LekoArts/minimal-blog-additional-field/commit/4d7a6da8c4d0191eff3ababfdb2466016ea751dd

Et voilá, the subtitle appeared:

image

Hope that helps! 😃

1reaction
LekoArtscommented, Jul 3, 2020

Found an even better way to access/set that data: https://github.com/LekoArts/gatsby-themes/issues/438

Read more comments on GitHub >

github_iconTop Results From Across the Web

fielddata mapping parameter | Elasticsearch Guide [8.5] | Elastic
Fix common cluster issues · Diagnose unassigned shards · Add a missing tier to the system · Allow Elasticsearch to allocate the data...
Read more >
How to fix this error Fielddata is disabled on text fields by ...
How to fix this error Fielddata is disabled on text fields by default. not want to add ""fielddata": true" · node.js · elasticsearch....
Read more >
Create basic field data in template like node for custom ...
Exception: Object of type Drupal\Core\Field\FieldItemList cannot be printed. If your entity defines id for the entity ID then {{ custom_entity.
Read more >
Reducing requested field data cache size of to the maximum ...
How to troubleshoot Elasticsearch/OpenSearch log "Reducing requested field data cache size of to the maximum allowed size of" a detailed guide including ...
Read more >
Programmatically copy field data in Drupal 8
Your solution is valid also for the fields create with the module: "Corresponding references"? Thanks.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found