Gatsby - Uncaught TypeError - Problema de contexto/compilação
Eu estava desenvolvendo meu aplicativo no Gatsby e travei. Tudo está funcionando bem com "gatsby develop", mas quando executo "gatsby build" recebo um erro:
"WebpackError: TypeError: Cannot destructure property 'cursorStyles' of 'Object(...)(...)' as it is undefined."
E sim, cursorStyles são definidos no contexto, então tudo deve funcionar perfeitamente ou estou perdendo alguma coisa. Tentei limpar o cache, mas ainda ocorre o erro, o que é muito estranho porque não tive problemas para trabalhar neste projeto localmente.
EDIT - sim, envolvi o aplicativo gatsby com o Provedor Global, como você pode ver abaixo. Só não entendo porque a compilação não funciona, quando claramente tenho acesso ao contexto... ;/
gatsby-browser.js
import React from "react"
import { GlobalProvider } from "./src/context/globalContext"
export const wrapRootElement = ({ element }) => {
return <GlobalProvider>{element}</GlobalProvider>
}
Contexto - os valores são definidos no provedor global const
import React, { createContext, useReducer, useContext } from "react"
//Define Context
const GlobalStateContext = createContext()
const GlobalDispatchContext = createContext()
//Reducer
const globalReducer = (state, action) => {
switch (action.type) {
case "TOGGLE_THEME": {
return {
...state,
currentTheme: action.theme,
}
}
case "CURSOR_TYPE": {
return {
...state,
cursorType: action.cursorType,
}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
export const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(globalReducer, {
currentTheme: "dark",
cursorType: false,
cursorStyles: ["pointer", "hovered", "locked", "white"],
})
return (
<GlobalDispatchContext.Provider value={dispatch}>
<GlobalStateContext.Provider value={state}>
{children}
</GlobalStateContext.Provider>
</GlobalDispatchContext.Provider>
)
}
//custom hooks for when we want to use our global state
export const useGlobalStateContext = () => useContext(GlobalStateContext)
export const useGlobalDispatchContext = () => useContext(GlobalDispatchContext)
Layout.js - o problema ocorre ao desestruturar e usar meu gancho personalizado
import React, {useState} from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import { createGlobalStyle, ThemeProvider } from "styled-components"
import { normalize } from "styled-normalize"
import Header from './header'
import Cursor from './customCursor'
import Navigation from './navigation'
import { useGlobalStateContext, useGlobalDispatchContext } from '../context/globalContext'
const Layout = ({ children }) => {
const { cursorStyles, currentTheme } = useGlobalStateContext()
const dispatch = useGlobalDispatchContext()
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
const darkTheme = {
background: '#000',
text:'#fff',
red: '#ea291e'
}
const lightTheme = {
background: '#fff',
text:'#000',
red: '#ea291e'
}
const onCursor = cursorType => {
cursorType = (cursorStyles.includes(cursorType) && cursorType || false)
dispatch({ type: "CURSOR_TYPE", cursorType: cursorType})
}
const [toggleMenu, setToggleMenu] = useState(false)
return(
<ThemeProvider theme={currentTheme === "dark" ? darkTheme : lightTheme}>
<GlobalStyle/>
<Cursor toggleMenu={toggleMenu} />
<Header onCursor={onCursor} toggleMenu={toggleMenu} setToggleMenu={setToggleMenu} />
<Navigation onCursor={onCursor} toggleMenu={toggleMenu} setToggleMenu={setToggleMenu} />
<main>{children}</main>
{console.log(currentTheme)}
</ThemeProvider>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
Respostas
Finalmente resolvi! Não sei por que, mas acho que é apenas Gatsby que trabalha de maneira misteriosa. Dupliquei meu código do navegador gatsby e coloquei exatamente a mesma coisa no arquivo gatsby-ssr e ... surpreendentemente, os erros estranhos sobre "objeto indefinido" desapareceram.
Infelizmente, devido ao fato de que a compilação do gatsby nesse caso funciona de maneira semelhante à renderização do lado do servidor do next.js, tive que corrigir meu código em lugares diferentes - por exemplo, as propriedades da "janela" tiveram que ser renderizadas condicionalmente - mas duplicar o gatsby- o código do navegador para o gatsby-ssr corrigiu o problema de construção! Então, como pensei, não era um problema com meu código, mas sim com a configuração do gatsby.