简体   繁体   中英

Modifying data from graphql queries into react components using gatsbyjs works in gatsby develop but breaks in gatsby build

I'm using prismic as a CMS for a website built with gatsby. I need to manipulate the data returned by graphql queries before rendering it in the react component. The website works fine in dev but the build fails because the variables I'm using are not defined at build time.

I've tried using componentDidMount and the hooks equivalent to define my variables only at mount time but it didn't work. I've also tried assigning the variable to the state of the component at mount time but that failed as well. See the code below, where I tried to make a simple example, for a better idea:

import { graphql } from 'gatsby';

import Layout from "../components/layout"

export const data = graphql`
  query allData {
    allPrismicNews{
      edges {
        node {
          id
        }
      }
    }
  }
`;



class IndexPage extends Component {
    render() {
      return (
        <Layout>
            <p>{this.state.newsId ? this.state.newsId : null}</p>
        </Layout>
      );
    }
  componentDidMount() {
    if (typeof window === 'undefined') {
        return;
    }
    this.setState(() => ({ newsId: this.props.data.allPrismicNews.edges.map(article=>article.node.id).flat() }));    
    }
  }
  export default IndexPage;```

For this example, I expect to see the ids of the news output in the template, this works in development but not in production.

What am I doing wrong?

What you could do is set an initial state to your newsId so that this.state.newsID is never undefined:

class IndexPage extends Component {
  state = {
    newsId: null,
  }
  componentDidMount() {
    if (typeof window === "undefined") {
      return
    }
    this.setState({
      newsId: this.props.data.allPrismicNews.edges
        .map(article => article.node.id)
        .flat(),
    })
  }
  render() {
    return (
      <Layout>
        <p>{this.state.newsId ? this.state.newsId : null}</p>
      </Layout>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM