You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.5 KiB
60 lines
1.5 KiB
import React, { createContext, useContext, useState, useEffect } from 'react'; |
|
import AsyncStorage from '@react-native-async-storage/async-storage'; |
|
|
|
type AuthContextType = { |
|
isLoggedIn: boolean; |
|
login: () => Promise<void>; |
|
logout: () => Promise<void>; |
|
}; |
|
|
|
const AuthContext = createContext<AuthContextType | null>(null); |
|
|
|
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { |
|
const [isLoggedIn, setIsLoggedIn] = useState(false); |
|
|
|
useEffect(() => { |
|
// 检查存储的登录状态 |
|
checkLoginStatus(); |
|
}, []); |
|
|
|
const checkLoginStatus = async () => { |
|
try { |
|
const value = await AsyncStorage.getItem('isLoggedIn'); |
|
setIsLoggedIn(value === 'true'); |
|
} catch (error) { |
|
console.error('Error checking login status:', error); |
|
} |
|
}; |
|
|
|
const login = async () => { |
|
try { |
|
await AsyncStorage.setItem('isLoggedIn', 'true'); |
|
setIsLoggedIn(true); |
|
} catch (error) { |
|
console.error('Error logging in:', error); |
|
} |
|
}; |
|
|
|
const logout = async () => { |
|
try { |
|
await AsyncStorage.setItem('isLoggedIn', 'false'); |
|
setIsLoggedIn(false); |
|
} catch (error) { |
|
console.error('Error logging out:', error); |
|
} |
|
}; |
|
|
|
return ( |
|
<AuthContext.Provider value={{ isLoggedIn, login, logout }}> |
|
{children} |
|
</AuthContext.Provider> |
|
); |
|
}; |
|
|
|
export const useAuth = () => { |
|
const context = useContext(AuthContext); |
|
if (!context) { |
|
throw new Error('useAuth must be used within an AuthProvider'); |
|
} |
|
return context; |
|
};
|