In my application I am integrating the context API.
I followed the Gatsby tutorial: https://www.gatsbyjs.org/blog/2019-01-31-using-react-context-api-with-gatsby/
When I am in local mode (gatsby development), my application loads the context data correctly.
But when I execute the gatby-build commands and then gatsby serve to test my application, the first time it loads it does not read the context data, but then when I navigate between the pages if I load the context data.
The tutorial suggests that you include the provider in gatsby-browser.js, but I just read that this file runs after the site loads.
Is this the problem? How could I solve this?
In local works perfect. In server mode no :(
file gatsby-browser.js
`
import React from 'react'
import { LangProvider } from './src/components/context/lang'
import { DataProvider } from './src/components/context/data'
export const wrapRootElement = ({ element }) => (
< DataProvider >
< LangProvider >
{ element }
LangProvider >
DataProvider >
)
`
System:
OS: Windows 10
CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
Binaries:
npm: 6.9.0 - C:\Program Files\nodejs\npm.CMD
Browsers:
Edge: 44.18362.267.0
npmPackages:
gatsby: ^2.13.59 => 2.13.59
gatsby-image: ^2.2.8 => 2.2.8
gatsby-plugin-create-client-paths: ^2.1.5 => 2.1.5
gatsby-plugin-manifest: ^2.2.5 => 2.2.5
gatsby-plugin-nprogress: ^2.1.2 => 2.1.2
gatsby-plugin-offline: ^2.2.5 => 2.2.5
gatsby-plugin-react-helmet: ^3.1.3 => 3.1.3
gatsby-plugin-sharp: ^2.2.11 => 2.2.11
gatsby-source-filesystem: ^2.1.9 => 2.1.9
gatsby-transformer-sharp: ^2.2.6 => 2.2.6
You need to use wrapRootElement in gatsby-ssr.js also.
// wrapRootElement.js
import React from 'react'
import { LangProvider } from './src/components/context/lang'
import { DataProvider } from './src/components/context/data'
export const wrapRootElement = ({ element }) => (
< DataProvider >
< LangProvider >
{ element }
</ LangProvider >
</ DataProvider >
)
// gatsby-browser.js
export { wrapRootElement } from './wrapRootElement'
// gatsby-ssr.js
export { wrapRootElement } from './wrapRootElement'
@universse thanks !!! The solution you have given me works perfectly.
@aikodeio I also followed the tutorial from the Gatsby docs but when I try to mount data from an API call using ComponentDidMount to setState inside the Context file I keep getting an error but I don't have this issue when I am not using ContextAPI.
Any takers? Thanks in advance.
Most helpful comment
You need to use
wrapRootElementingatsby-ssr.jsalso.