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?
this.state && this.state.newsIdin the ternary operator condition. I am wondering if this is the correct way of manipulating data coming from a graphql query in gatsbyjsnewsIdso thatthis.state.newsIdwill never beundefined.