I try to implement this tutorial /router/reference/authentication/
and get my 2 files in ctx folder like this
ctx/ctx.ts
import { useContext, createContext, type PropsWithChildren } from 'react';
import { useStorageState } from './useStorageState';
import {userSession} from '@/design/objectType'
const AuthContext = createContext<{
signIn: (sesionObj:any) => void;
signOut: () => void;
session?: string | null;
isLoading: boolean;
}>({
signIn: () => null,
signOut: () => null,
session: null,
isLoading: false,
});
// This hook can be used to access the user info.
export function useSession() {
const value = useContext(AuthContext);
if (process.env.NODE_ENV !== 'production') {
if (!value) {
throw new Error('useSession must be wrapped in a <SessionProvider />');
}
}
return value;
}
export function SessionProvider({ children }: PropsWithChildren) {
const [[isLoading, session], setSession] = useStorageState('session');
return (
<AuthContext.Provider
value={{
signIn: (sesionObj:any) => {
// Perform sign-in logic here
console.log(sesionObj);
setSession(sesionObj);
},
signOut: () => {
setSession(null);
},
session,
isLoading,
}}>
{children}
</AuthContext.Provider>
);
}
useStorageState.ts
import { useEffect, useCallback, useReducer } from 'react';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
type UseStateHook<T> = [[boolean, T | null], (value: T | null) => void];
function useAsyncState<T>(
initialValue: [boolean, T | null] = [true, null],
): UseStateHook<T> {
return useReducer(
(state: [boolean, T | null], action: T | null = null): [boolean, T | null] => [false, action],
initialValue
) as UseStateHook<T>;
}
export async function setStorageItemAsync(key: string, value: string | null) {
if (Platform.OS === 'web') {
try {
if (value === null) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, value);
}
} catch (e) {
console.error('Local storage is unavailable:', e);
}
} else {
if (value == null) {
await SecureStore.deleteItemAsync(key);
} else {
await SecureStore.setItemAsync(key, value);
}
}
}
export function useStorageState(key: string): UseStateHook<string> {
// Public
const [state, setState] = useAsyncState<string>();
// Get
useEffect(() => {
if (Platform.OS === 'web') {
try {
if (typeof localStorage !== 'undefined') {
setState(localStorage.getItem(key));
}
} catch (e) {
console.error('Local storage is unavailable:', e);
}
} else {
SecureStore.getItemAsync(key).then(value => {
setState(value);
});
}
}, [key]);
// Set
const setValue = useCallback(
(value: string | null) => {
setState(value);
setStorageItemAsync(key, value);
},
[key]
);
return [state, setValue];
}
the problem is everytime i exit the app, it always return null
when i try to get session, is there something wrong on how i implement this tutorial?