useContext() not working in Layout.jsx
Answered
Caribbean Elaenia posted this in #help-forum
Caribbean ElaeniaOP
When I use useContext() inside layout.jsx, it returns me an error: TypeError: reactWEBPACK_IMPORTED_MODULE_4.useContext(...) is undefined.
I'm not sure why's that. Assistance is needed and appreciated!
I'm not sure why's that. Assistance is needed and appreciated!
Answered by Jesse677
This is how I implement it.
// layout.tsx
export default async function Layout({ children }) {
const user = getUserFromHeaders();
return (
<UserStateProvider user={user}>
{children}
</UserStateProvider>
);
}
// UserStateProvider
"use client";
const UserContext = createContext({} as UserType);
export const useUser = () => useContext(UserContext);
const UserStateProvider = ({ children, user }: PropsType) => {
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
export default UserStateProvider;
12 Replies
Caribbean ElaeniaOP
@Jesse677
This is how I implement it.
// layout.tsx
export default async function Layout({ children }) {
const user = getUserFromHeaders();
return (
<UserStateProvider user={user}>
{children}
</UserStateProvider>
);
}
// UserStateProvider
"use client";
const UserContext = createContext({} as UserType);
export const useUser = () => useContext(UserContext);
const UserStateProvider = ({ children, user }: PropsType) => {
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
export default UserStateProvider;
Answer
Caribbean ElaeniaOP
I think it's fixed now
💀
I'm not sure how
Oh I know why
This:
export const ThemeContext = createContext();
I have to add an array
export const ThemeContext = createContext({});
Like this
It worked fine now
thanks