UNPKG

2.69 kBJavaScriptView Raw
1import React from "react"
2import PropTypes from "prop-types"
3import Link, {
4 withPrefix,
5 withAssetPrefix,
6 navigate,
7 push,
8 replace,
9 navigateTo,
10 parsePath,
11} from "gatsby-link"
12import PageRenderer from "./public-page-renderer"
13import loader from "./loader"
14
15const prefetchPathname = loader.enqueue
16
17const StaticQueryContext = React.createContext({})
18
19function StaticQueryDataRenderer({ staticQueryData, data, query, render }) {
20 const finalData = data
21 ? data.data
22 : staticQueryData[query] && staticQueryData[query].data
23
24 return (
25 <React.Fragment>
26 {finalData && render(finalData)}
27 {!finalData && <div>Loading (StaticQuery)</div>}
28 </React.Fragment>
29 )
30}
31
32const StaticQuery = props => {
33 const { data, query, render, children } = props
34
35 return (
36 <StaticQueryContext.Consumer>
37 {staticQueryData => (
38 <StaticQueryDataRenderer
39 data={data}
40 query={query}
41 render={render || children}
42 staticQueryData={staticQueryData}
43 />
44 )}
45 </StaticQueryContext.Consumer>
46 )
47}
48
49const useStaticQuery = query => {
50 if (
51 typeof React.useContext !== `function` &&
52 process.env.NODE_ENV === `development`
53 ) {
54 throw new Error(
55 `You're likely using a version of React that doesn't support Hooks\n` +
56 `Please update React and ReactDOM to 16.8.0 or later to use the useStaticQuery hook.`
57 )
58 }
59 const context = React.useContext(StaticQueryContext)
60 if (context[query] && context[query].data) {
61 return context[query].data
62 } else {
63 throw new Error(
64 `The result of this StaticQuery could not be fetched.\n\n` +
65 `This is likely a bug in Gatsby and if refreshing the page does not fix it, ` +
66 `please open an issue in https://github.com/gatsbyjs/gatsby/issues`
67 )
68 }
69}
70
71StaticQuery.propTypes = {
72 data: PropTypes.object,
73 query: PropTypes.string.isRequired,
74 render: PropTypes.func,
75 children: PropTypes.func,
76}
77
78function graphql() {
79 throw new Error(
80 `It appears like Gatsby is misconfigured. Gatsby related \`graphql\` calls ` +
81 `are supposed to only be evaluated at compile time, and then compiled away. ` +
82 `Unfortunately, something went wrong and the query was left in the compiled code.\n\n` +
83 `Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.`
84 )
85}
86
87export {
88 Link,
89 withAssetPrefix,
90 withPrefix,
91 graphql,
92 parsePath,
93 navigate,
94 push, // TODO replace for v3
95 replace, // TODO remove replace for v3
96 navigateTo, // TODO: remove navigateTo for v3
97 StaticQueryContext,
98 StaticQuery,
99 PageRenderer,
100 useStaticQuery,
101 prefetchPathname,
102}