Reputation: 77
I'm trying to create a SessionProvider to avoid propdrilling and hold session globally for my components.
But it is saying useSession is not a function, what gives?
contexts\SessionContext.js: TypeError: (0 , _hooks_useSession__WEBPACK_IMPORTED_MODULE_2__.useSession) is not a function
My custom hook (useSession.js):
import { useState } from 'react'
function useSession(isLoggedInState) {
const [isLoggedIn, setIsLoggedIn] = useState(isLoggedInState);
return { isLoggedIn, setIsLoggedIn, }
}
export default useSession;
My provider (SessionContext.js):
import React, { createContext, useState } from 'react'
import { useSession } from '../hooks/useSession'
const SessionContext = createContext();
function SessionProvider({ children, isLoggedin = false }) {
const { isLoggedIn, setIsLoggedIn } = useSession(isLoggedin);
return (
<SessionContext.Provider value={isLoggedIn, setIsLoggedIn}>{children}</SessionContext.Provider>
)
}
export { SessionProvider, SessionContext };
I've wrapped my application using in _app.js and then in Home (index.js) I try to use it there:
import React from 'react'
import { Text, TextContainer } from 'react-md'
import { useContext } from "react";
import { SessionContext } from "../contexts/SessionContext";
export default function Home() {
const { isLoggedIn, setIsLoggedIn } = useContext(SessionContext);
return (
<TextContainer>
<Text type="headline-4">Hello, world!</Text>
</TextContainer>
)
}
Anyone see where I went wrong?
Upvotes: 5
Views: 10419
Reputation: 1962
There are few places where you've done some mistakes.
first one is in SessionContext.js
. In here, you're importing useSession
as a variable import where, you've export useSession
as default export from useSession.js
file.
So fix this one
// SessionContext.js
import useSession from '../hooks/useSession'
...
And second one is: you can't use useContext(SessionContext)
there because your Home component is not a children of SessionProvider
.
So Yo need to wrap your home component
by SessionProvider
.
Here is the fix code:
// index.js
import { SessionContext, SessionProvider } from "../contexts/SessionContext";
const Main = () => {
return (
<SessionProvider>
<Home />
</SessionProvider>
);
};
const Home = () => {
const { isLoggedIn, setIsLoggedIn } = useContext(SessionContext);
return (
<TextContainer>
<Text type="headline-4">Hello, world!</Text>
</TextContainer>
)
}
export default main
Upvotes: 1
Reputation: 886
You need to change the way your "useSession" hook is imported in the SessionContext.js.
It should be imported like this (without curly brackets) since you are exporting it as a default component.
import useSession from '../hooks/useSession'
Upvotes: 8