Vad
Vad

Reputation: 3740

React Context Does Not Propagate Changes to Other Consumers After Successful Provider Update

This is my first React Context implementation. I am using Gatsby and in my layout.js I added Context (with objects and handler function) that successfully gets passed to Consumer:

  import AppContext from "./AppContext"

  const Layout = ({ children }) => {

  let doAuthenticate = () => {
    authState = {
      isAuth: authState.isAuth === true ? false : true,
    }
  }

  let authState = { 
    isAuth: false,
    doAuthenticate: doAuthenticate
  }

  return (
    <>
      <AppContext.Provider value={authState}>
        <main>{children}</main>
      </AppContext.Provider>
    </>
  )

I successfully execute function in Consumer:

<AppContext.Consumer>
   { value =>
      <button onClick={value.doAuthenticate}Sign in</button>
    }
</AppContext.Consumer>

I also see the value in doAuthenticate successfully gets updated.

However, another Consumer that is listening to Provider does not update the value. Why?

Upvotes: 2

Views: 705

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

When you use Gatsby, each instance of the Page will we wrapped with the Layout component and hence you will see that instead of creating one Context that is shared between pages, you end up creating multiple contexts.

Now multiple contexts cannot communicate with each other

The solution here is to make use of wrapRootElement api in gatsby-ssr.js and gatsby-browser.js to wrap all your pages with a single layout component

import React from "react";
import Layout from "path/to/Layout";


const wrapRootElement = ({ element }) => {
  return (
    <Layout>
      {element}
    </Layout>
  )
}

export { wrapRootElement };

Upvotes: 2

Related Questions