Context undefined

I want to wrap my auth token from local storage in a ContextProvider. To this effect I've done this:
const TokenContext = createContext();

export function TokenProvider(props) {
const [getToken, setToken, {remove}] = createStorageSignal('token', { api: cookieStorage }),
token = [getToken,{login(token) {setToken(token)}, logout() {remove()}}];
return <TokenContext.Provider value={token}>{props.children}</TokenContext.Provider>
}

export function useToken() { return useContext(TokenProvider); }
const TokenContext = createContext();

export function TokenProvider(props) {
const [getToken, setToken, {remove}] = createStorageSignal('token', { api: cookieStorage }),
token = [getToken,{login(token) {setToken(token)}, logout() {remove()}}];
return <TokenContext.Provider value={token}>{props.children}</TokenContext.Provider>
}

export function useToken() { return useContext(TokenProvider); }
What am i doing wrong?
3 Replies
FjordWarden
FjordWardenOP2y ago
The context providers works with the counter example from the docs, so maybe it could be something with the solid start localStorage
Alex Lohr
Alex Lohr2y ago
Can you please show where you use the context?
FjordWarden
FjordWardenOP2y ago
I use it in a function like this:
function Login(props) {
const [searchParams, setSearchParams] = useSearchParams();
const [token, {login}] = useToken();
createEffect(()=>{if (searchParams.token) login(searchParams.token)})
function Login(props) {
const [searchParams, setSearchParams] = useSearchParams();
const [token, {login}] = useToken();
createEffect(()=>{if (searchParams.token) login(searchParams.token)})
Then I also have the TokenProvider in the root of my app:
render(() => (
<CounterProvider count={1}>
<TokenProvider>
<Router>
<div class="h-screen bg-neutral-900">
<Routes>
// ...
</Routes>
</div>
</Router>
</TokenProvider>
</CounterProvider>
), document.body);
render(() => (
<CounterProvider count={1}>
<TokenProvider>
<Router>
<div class="h-screen bg-neutral-900">
<Routes>
// ...
</Routes>
</div>
</Router>
</TokenProvider>
</CounterProvider>
), document.body);
Ok, I found the problem, just put the TokenProvider in useContext instead of TokenContext
Want results from more Discord servers?
Add your server