Доступ к данным из массива в запросе Gatsby Graphql - PullRequest
0 голосов
/ 08 февраля 2020

Я становлюсь тупым здесь. У меня есть сайт Gatsby, который я настраиваю с помощью netlify cms. У меня установлен конфигурационный файл, и я могу создавать страницы и виджеты из netlify admin. Когда я запускаю свой запрос graphql, я могу получить информацию о странице, но не могу получить доступ к данным из виджета.

admin / config.yml

  name: git-gateway
  branch: master # Branch to update (optional; defaults to master)

media_folder: "src/images" # Media files will be stored in the repo under static/images/uploads

collections:
  - name: "pages"
    label: "Page"
    folder: "src/markdown-pages"
    create: true
    fields:
      - {label: "Title", name: "title"}
      - {label: "Content", name: "content"}
      - {label: "Slug", name: "slug"}
      - {label: "Path", name: "path"}
      - label: "Page Sections"
        name: "sections"
        widget: "list"
        types:
          - label: "Call To Action"
            name: "calltoaction"
            widget: object
            fields:
              - {label: "Title", name: "title", widget: "string"}
              - {label: "Content", name: "content", widget: "markdown", required: false}
              - {label: "Call to Action Link", name: "link", widget: "string", required: false, hint: "Call to Action Link"}
              - {label: "Call to Action Text", name: "buttontext", widget: "string", required: false, hint: "Call to Action Text"}
          - label: "Services"
            name: "services"
            widget: object
            fields:
              - {label: "Title", name: "title", widget: "string"}
              - {label: "Content", name: "content", widget: "markdown", required: false}

gatsby- node.js


exports.createPages = ({actions, graphql}) => {
  const {createPage} = actions;

  const pageTemplate = path.resolve('src/templates/page.js');
  return graphql(`{
    allMarkdownRemark {
      edges {
        node {

          id
          frontmatter {
            title
            path
            sections {
              buttontext
              content
              link
              title
            }
          }
        }
      }
    }
  }`)
  .then(result => {
    if (result.errors) {
      result.errors.forEach(e => console.error(e.toString()))
      return Promise.reject(result.errors)
    }

    result.data.allMarkdownRemark.edges.forEach(({node}) => {
      createPage({
        path: node.frontmatter.path,
        component: pageTemplate,
        context: {
          id: node.id,
        }
      })
    })
  })
}

pagetemplate. js

import Helmet from 'react-helmet'
import Layout from "../components/layout"
//import CTA from '../components/sections/CTA-section'

export default function Template({ data }) {
  const {markdownRemark: page} = data

return (
  <Layout>
    <h1>{page.frontmatter.title}</h1>
    <p>{page.frontmatter.sections.title}</p>
    // <CTA />
  </Layout> 
)
}

export const pageQuery = graphql`
  query pageByPath($id: String!) {
    markdownRemark(id: { eq: $id } ) {
      id
      frontmatter {
        path
        title
        sections {
          title
          buttontext
          content
          link
        }
      }
    }
  }
`

Скриншот GraphiQL Скриншот graphiql

Бонусный вопрос: мне также нужно выяснить, как сделать компонент для этих виджетов. Как вы можете видеть из закомментированных строк в шаблоне страницы. js Я хотел бы сделать отдельные компоненты для каждого виджета. Поскольку данные являются динамическими c, я не думаю, что смогу использовать StaticQuery, и я не могу сделать еще один запрос страницы к тем же данным, поскольку они будут импортированы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...