Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create context state for login and logout #120

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions client/src/context/app/state.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
LOGIN,
} from '../types';

const AppState = (props) => {
Expand Down
28 changes: 28 additions & 0 deletions client/src/context/auth-context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createContext, useReducer } from "react";

export const AuthContext = createContext();

export const authReducer = (state, action) => {
switch (action.type) {
case "LOGIN":
return { user: action.payload };
case "LOGOUT":
return { user: null };
default:
return state;
}
}

export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(AuthReducer, {
user: null
});

return (
<AuthContext.Provider
value={{...state, dispatch}}
>
{children}
</AuthContext.Provider>
);
}
11 changes: 11 additions & 0 deletions client/src/hooks/useAuthContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { AuthContext } from "../context/auth-context/AuthContext";
import { useContext } from "react";

export const useAuthContext = () => {
const context = useContext(AuthContext);

if (context === undefined) {
throw new Error("useAuthContext must be used within a AuthContextProvider");
}
return context;
}
9 changes: 6 additions & 3 deletions client/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import theme from './theme';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App.jsx';
import { AuthContextProvider } from './context/auth-context/AuthContext.js';

ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
<AuthContextProvider>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</AuthContextProvider>
</React.StrictMode>
);
Loading