On routes/index.tsx
I have:
import GrandChildComponent from "../components/GrandChildComponent.tsx";
import { Username } from "./context.ts";
export default function App() {
return (
<Username.Provider value="Bob">
<GrandChildComponent />
</Username.Provider>
)
}
On context.ts
I have:
import { createContext } from 'preact'
export const Username = createContext('alice')
If on components/GrandChildComponent.tsx
I use:
import { Username } from "../routes/context.ts";
export default function GrandChildComponent(){
return (
<Username.Consumer>
{username => (
// access the current username from context:
<span>{username}</span>
)}
</Username.Consumer>
)
}
then it works as expected. But if I want to use the useContext
hook instead:
import { useContext } from "preact/hooks";
import { Username } from "../routes/context.ts";
export default function GrandChildComponent(){
const username = useContext(Username)
return <span>{username}</span>
}
I get this error:
3 |
4 | export default function ComponentCon(){
> 5 | const username = useContext(Username) // "Bob"
| ^
6 | return <span>{username}</span>
7 | }
TypeError: Cannot read properties of null (reading 'context')
I’m not sure where it’s wrong.