Currently, I am delving into NextJs and encountering an issue with utilizing context.
Below is the snippet of my context:
"use client";
import { createContext, useContext, useState } from "react";
const UserAuthContext = createContext();
export function UserAuthWrapper({ children }) {
const [user, setUser] = useState({ name: "test user" });
return (
<UserAuthContext.Provider value={[user, setUser]}>
{children}
</UserAuthContext.Provider>
);
}
export function useUserAuthContext() {
return useContext(UserAuthContext);
}
However, a problem arises when trying to retrieve the user object using useUserAuthContext
. The error message displayed is as follows:
TypeError: (0 , _context_user_auth_context__WEBPACK_IMPORTED_MODULE_2__.useUserAuthContext) is not a function or its return value is not iterable
at Home (./src/app/page.js:14:93)
at stringify (<anonymous>)
Shown below is how the UserAuthWrapper is implemented in the RootLayout file:
import { Inter } from "next/font/google";
import "./globals.css";
import { UserAuthWrapper } from "./context/user-auth.context";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className={inter.className}>
<UserAuthWrapper>{children}</UserAuthWrapper>
</body>
</html>
);
}
Here's an example of how I utilize the function:
import { useUserAuthContext } from "./context/user-auth.context";
export default function Home() {
const [user, setUser] = useUserAuthContext();
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div>{user.name}</div>
</main>
);
}
Recent Update
============================
I decided to conduct another test on my Home page:
import Image from "next/image";
import { useUserAuthContext } from "./context/user-auth.context";
export default function Home() {
const a = useUserAuthContext();
console.log(a);
const [user, setUser] = useUserAuthContext();
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div>{user.name}</div>
</main>
);
}
After running this additional test, the error now reads as:
src\app\page.js (5:30) @ useUserAuthContext
⨯ TypeError: (0 , _context_user_auth_context__WEBPACK_IMPORTED_MODULE_2__.useUserAuthContext) is not a function
at Home (./src/app/page.js:14:93)
at stringify (<anonymous>)
digest: "1948578294"
3 |
4 | export default function Home() {
> 5 | const a = useUserAuthContext();
| ^
Below is the layout of my file/folder structure: