Unable to use auth context, but can use this another context?
Unanswered
Saltwater Crocodile posted this in #help-forum
Saltwater CrocodileOP
i have taken an auth-context from one of my older NextJS projects
"use client";
import { createContext, useContext, useEffect, useReducer, useRef } from 'react';
import PropTypes from 'prop-types';
const HANDLERS = {
INITIALIZE: 'INITIALIZE',
SIGN_IN: 'SIGN_IN',
SIGN_OUT: 'SIGN_OUT'
};
const initialState = {
isAuthenticated: false,
isLoading: true,
user: null
};
const handlers = {
[HANDLERS.INITIALIZE]: (state, action) => {
const user = action.payload;
return {
...state,
...(
// if payload (user) is provided, then is authenticated
user
? ({
isAuthenticated: true,
isLoading: false,
user
})
: ({
isLoading: false
})
)
};
},
[HANDLERS.SIGN_IN]: (state, action) => {
// code for that
},
[HANDLERS.SIGN_OUT]: (state) => {
// code for that
};
const reducer = (state, action) => (
handlers[action.type] ? handlers[action.type](state, action) : state
);
export const AuthContext = createContext({ undefined });
export const AuthProvider = (props) => {
/// bunch of code
};
useEffect(
() => {
initialize();
},
[]
);
const skip = () => {
//skip authentication
};
const signIn = async (email, password) => {
// sign in code
};
const signUp = async (email, name, password) => {
throw new Error('Sign up is not implemented');
};
const signOut = () => {
dispatch({
type: HANDLERS.SIGN_OUT
});
};
return (
<AuthContext.Provider
value={{
...state,
skip,
signIn,
signUp,
signOut
}}
>
{children}
</AuthContext.Provider>
);
};
AuthProvider.propTypes = {
children: PropTypes.node
};
export const AuthConsumer = AuthContext.Consumer;
export const useAuthContext = () => useContext(AuthContext);2 Replies
Saltwater CrocodileOP
the problem is, im unable to useContext this thing, because all I see is
now, ideally this null property will be overwritten by AuthProvider, and it does in my older NextJS project. However, I just moved to
THIS thing works for some reason and i can simply access it with useContext(counter) but for some reason that above code doesn't work!
{undefined} because of this line:export const AuthContext = createContext({ undefined });now, ideally this null property will be overwritten by AuthProvider, and it does in my older NextJS project. However, I just moved to
NextJS 13 and file stucture has changed. I did pass AuthProvider in layout.jsx , but its still the same problem. I was under the impression that perhaps this could be a problem with how ContextAPIs work in NextJS 13, so i followed this tutorial, which, tldr, creates a simple counter Context (for incrementing/decrementing counter) https://codevoweb.com/setup-react-context-api-in-nextjs-13-app-directory/THIS thing works for some reason and i can simply access it with useContext(counter) but for some reason that above code doesn't work!
this is the full code!