Unable to import user context function
Answered
Cicada killer posted this in #help-forum
Cicada killerOP
I'm trying to setup a user context for my NextJS web application, but everytime i import the hook into any of the pages. It throws me an error:
Note: I've already wrapped the provider in the
I'm not sure exactly why it is unable to see this as a function?
Here is the page that I'm importing the context.
Here is the
Error: (0 , _hooks_useUser__WEBPACK_IMPORTED_MODULE_2__.useUser) is not a function. Note: I've already wrapped the provider in the
layout.tsxI'm not sure exactly why it is unable to see this as a function?
Here is the page that I'm importing the context.
import { NextPage } from "next";
import Page from "@/components/Page";
import { useUser } from "@/hooks/useUser";
const Home: NextPage = () => {
const { user } = useUser();
return (
<Page />
);
};
export default Home;Here is the
useUser.tsx"use client"
import { LoginDetails, User } from "@/util/types/user";
import React, { FC, ReactNode, useContext, useState } from "react";
import urls from "@/util/types/APIs";
export type UserProfile = {
user?: User;
login: (loginDetails: LoginDetails) => Promise<void>;
logout: () => Promise<void>;
};
export const UserProfileContext = React.createContext<UserProfile | undefined>(undefined);
export const UserContextProvider: FC<{
children: ReactNode;
}> = ({ children }) => {
const [ user, setUser ] = useState<User | undefined>(undefined);
const login = async (loginDetails: LoginDetails) => {
...
}
const logout = async () => {
...
}
const context: UserProfile = {
user,
login,
logout,
};
return (
<UserProfileContext.Provider value={context}>
{children}
</UserProfileContext.Provider>
);
}
export const useUser = () => {
const context = useContext(UserProfileContext);
if (context === undefined) {
throw new Error("useUser must be used within a UserContextProvider");
}
return context;
}9 Replies
Cicada killerOP
yes @Ray I am using app router
you cannot use hook in the Home component because its a server component
Cicada killerOP
So if I want to use like "useUser()" id have to call it in "use client" components?
yes
or components that are inside of another "use client" components
Answer
unless your
useUser() doesn't use any react hooksCicada killerOP
ok thank you! I think I got it. Thanks so much