Gatsby: State of context is lost after using <Link> or navigate()

Created on 25 Mar 2020  路  1Comment  路  Source: gatsbyjs/gatsby

I'm using the react context API to store some application-wide state information. This works fine on a single page.

However, if I use <Link> or navigate() to go to a different page, and then use the react dev tools to look at the context provider, its state is completely gone.

Is that the expected behavior? If yes, what is the alternative to using the context API?

question or discussion

Most helpful comment

I found this blog post that shows an example of using context with gatsby.

The issue was that I put the in the root layout, thinking that was sufficient. I actually needed to put it in gatsby-browser.js

import React from 'react';                 
import PropTypes from 'prop-types';        
import "./src/css/style.css";              
import ProfileContext from "./src/context/profile/profile-state"; 

export const wrapRootElement = ({ element }) => ( 
   <ProfileContext>{element}</ProfileContext> 
)                                          

wrapRootElement.propTypes = {              
  element: PropTypes.node                  
}

>All comments

I found this blog post that shows an example of using context with gatsby.

The issue was that I put the in the root layout, thinking that was sufficient. I actually needed to put it in gatsby-browser.js

import React from 'react';                 
import PropTypes from 'prop-types';        
import "./src/css/style.css";              
import ProfileContext from "./src/context/profile/profile-state"; 

export const wrapRootElement = ({ element }) => ( 
   <ProfileContext>{element}</ProfileContext> 
)                                          

wrapRootElement.propTypes = {              
  element: PropTypes.node                  
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

rossPatton picture rossPatton  路  3Comments

hobochild picture hobochild  路  3Comments

dustinhorton picture dustinhorton  路  3Comments

jimfilippou picture jimfilippou  路  3Comments

magicly picture magicly  路  3Comments