I am trying to refactor an app to use useContext but have hit a snag and cannot figure out what is happening.
Using the latest version of everything, running Next.js.
The way things are structured is that every page is wrapped in <Layout> and some pages are also wrapped in <Fund>, nested under <Layout>.
I have global context that is set in _app.js and passed to Layout where it is rendered. This works fine, the aTest context variable that I define in pages/_app.js renders on Layout and shows on all pages.
Then I have fund-specific context that is set in components/Fund.js and loaded in on pages/fund/index.js (and subsequent other pages).
This does not work. The anotherTest context variable that I define in /components/Fund.js is not showing in /pages/fund/index.js even though the return statement there is wrapped in the <Fund> component (which I assume should hold and pass on the context).
I think I have maybe got my child/parent order mixed up for the non-working scenario but by brain is fried. Any tips?
Stripped back, the basic code is:
/components/
- UserContext.js
- FundContext.js
- Layout.js
- Fund.js
/pages/
- _app.js
- index.js
- /fund/
- index.js
Both the /components/*Context.js files are the same bar the names declared in them:
import { createContext } from 'react';
const FundContext = createContext();
export default FundContext;
and
import { createContext } from 'react';
const UserContext = createContext();
export default UserContext;
In /pages/_app.js I am doing:
import React, { useState } from "react";
import UserContext from '../components/UserContext';
...
function MyApp({ Component, pageProps }) {
...
return (
<UserContext.Provider value={{
aTest: "This is a test"
}}>
<Component {...pageProps} />
</UserContext.Provider>
)
}
export default MyApp
In /components/Layout.js I am doing:
import React, { useState, useContext } from "react";
import UserContext from './UserContext';
const Layout = ({children}) => {
let {aTest} = useContext(UserContext);
return (
<main>
<h1>{aTest}</h1>
{children}
</main>
)
}
export default Layout
In /components/Fund.js I am doing:
import React, { useState, useContext } from "react";
import UserContext from './FundContext';
const Fund = ({children}) => {
return (
<main>
<h1>{aTest}</h1>
<FundContext.Provider value={{ anotherTest: "Just another test" }}>
{children}
</FundContext.Provider>
</main>
)
}
export default Layout
In /pages/fund/index.js I am doing:
import React, { useState, useContext } from "react";
import FundContext from '../../components/FundContext';
...
export default function App () {
let {anotherTest} = useContext(FundContext);
return (
<Fund>
{anotherTest}
</Fund>
)
}