UNPKG

2.73 kBJavaScriptView Raw
1import React from "react"
2
3import PageRenderer from "./page-renderer"
4import normalizePagePath from "./normalize-page-path"
5import { StaticQueryContext } from "gatsby"
6import {
7 getStaticQueryData,
8 getPageQueryData,
9 registerPath as socketRegisterPath,
10 unregisterPath as socketUnregisterPath,
11} from "./socketIo"
12
13if (process.env.NODE_ENV === `production`) {
14 throw new Error(
15 `It appears like Gatsby is misconfigured. JSONStore is Gatsby internal ` +
16 `development-only component and should never be used in production.\n\n` +
17 `Unless your site has a complex or custom webpack/Gatsby ` +
18 `configuration this is likely a bug in Gatsby. ` +
19 `Please report this at https://github.com/gatsbyjs/gatsby/issues ` +
20 `with steps to reproduce this error.`
21 )
22}
23
24const getPathFromProps = props =>
25 props.pageResources && props.pageResources.page
26 ? normalizePagePath(props.pageResources.page.path)
27 : undefined
28
29class JSONStore extends React.Component {
30 constructor(props) {
31 super(props)
32 this.state = {
33 staticQueryData: getStaticQueryData(),
34 pageQueryData: getPageQueryData(),
35 path: null,
36 }
37 }
38
39 handleMittEvent = (type, event) => {
40 this.setState({
41 staticQueryData: getStaticQueryData(),
42 pageQueryData: getPageQueryData(),
43 })
44 }
45
46 componentDidMount() {
47 socketRegisterPath(getPathFromProps(this.props))
48 ___emitter.on(`*`, this.handleMittEvent)
49 }
50
51 componentWillUnmount() {
52 socketUnregisterPath(this.state.path)
53 ___emitter.off(`*`, this.handleMittEvent)
54 }
55
56 static getDerivedStateFromProps(props, state) {
57 const newPath = getPathFromProps(props)
58 if (newPath !== state.path) {
59 socketUnregisterPath(state.path)
60 socketRegisterPath(newPath)
61 return {
62 path: newPath,
63 }
64 }
65
66 return null
67 }
68
69 shouldComponentUpdate(nextProps, nextState) {
70 // We want to update this component when:
71 // - location changed
72 // - page data for path changed
73 // - static query results changed
74
75 return (
76 this.props.location !== nextProps.location ||
77 this.state.path !== nextState.path ||
78 this.state.pageQueryData[normalizePagePath(nextState.path)] !==
79 nextState.pageQueryData[normalizePagePath(nextState.path)] ||
80 this.state.staticQueryData !== nextState.staticQueryData
81 )
82 }
83
84 render() {
85 const data = this.state.pageQueryData[getPathFromProps(this.props)]
86 // eslint-disable-next-line
87 if (!data) {
88 return <div />
89 }
90
91 return (
92 <StaticQueryContext.Provider value={this.state.staticQueryData}>
93 <PageRenderer {...this.props} {...data} />
94 </StaticQueryContext.Provider>
95 )
96 }
97}
98
99export default JSONStore