0

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?
3
  • I was able to fix the build by adding this.state && this.state.newsId in the ternary operator condition. I am wondering if this is the correct way of manipulating data coming from a graphql query in gatsbyjs Commented May 25, 2019 at 9:44
  • You could set an initial state for newsId so that this.state.newsId will never be undefined. Commented May 26, 2019 at 2:28
  • 1
    thanks @RobertCooper, I think that's the cleanest way to do this. Commented May 26, 2019 at 16:33

1 Answer 1

1

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>
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.