-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAuth.js
More file actions
55 lines (45 loc) · 1.69 KB
/
useAuth.js
File metadata and controls
55 lines (45 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import React, { useState, createContext, useContext, useEffect } from "react";
import { initialUsers } from "../data/initialUsers";
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
// Use localStorage to persist user data
const [users, setUsers] = useState(() => {
const savedUsers = localStorage.getItem('users');
return savedUsers ? JSON.parse(savedUsers) : initialUsers;
});
const [currentUser, setCurrentUser] = useState(null);
// Save users to localStorage whenever they change
useEffect(() => {
localStorage.setItem('users', JSON.stringify(users));
}, [users]);
const login = (email, password) => {
const user = users.find((u) => u.email === email && u.password === password);
if (user) {
// Create a deep copy to avoid direct state mutation
const userCopy = JSON.parse(JSON.stringify(user));
setCurrentUser(userCopy);
}
return user || null;
};
const logout = () => setCurrentUser(null);
const updateUserProfile = (updatedProfile) => {
// Update the users array
const updatedUsers = users.map(user =>
user.id === updatedProfile.id ? { ...user, ...updatedProfile } : user
);
setUsers(updatedUsers);
setCurrentUser(updatedProfile);
};
return (
<AuthContext.Provider value={{
currentUser,
users,
login,
logout,
updateUserProfile
}}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);