context/AuthContext.tsx
Код: Выделить всё
import * as SecureStore from "expo-secure-store";
import { createContext, useContext, useEffect, useState } from "react";
interface AuthProps {
//authState nos dará información del estado del usuario como token, si está autenticado y el id del usuario
authState: {
token: string | null;
authenticated: boolean | null;
user_id: string | null;
};
onRegister: (email: string, password: string) => Promise;
onLogin: (email: string, password: string) => Promise;
onLogout: () => Promise;
initialized: boolean;
}
const TOKEN_KEY = "my-stream-token";
export const API_URL = process.env.EXPO_PUBLIC_SERVER_URL;
const AuthContext = createContext
>({}); //Creamos el contexto de autenticación
//Creamos el provider de autenticación que se encargará de manejar el estado de autenticación
export const useAuth = () => {
return useContext(AuthContext);
};
export const AuthProvider = ({ children }: any) => {
const [authState, setAuthState] = useState({
token: null,
authenticated: null,
user_id: null,
});
const [initialized, setInitialized] = useState(false);
//Obtener el token del usuario
useEffect(() => {
const loadToken = async () => {
//Cargar token al iniciar
const data = await SecureStore.getItemAsync(TOKEN_KEY);
if (data) {
const object = JSON.parse(data);
//Establecemos nuestro estado de contexto
setAuthState({
token: object.token,
authenticated: true,
user_id: object.user.id,
});
}
setInitialized(true);
};
loadToken();
}, []);
//Iniciar sesión
const login = async (email: string, password: string) => {
try {
//Hacer la petición al servidor
const result = await fetch(`${API_URL}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
const json = await result.json();
//Estado de autenticación
setAuthState({
token: json.token,
authenticated: true,
user_id: json.user.id,
});
//Guardar el token en el almacenamiento seguro
await SecureStore.setItemAsync(TOKEN_KEY, JSON.stringify(json));
return json;
} catch (e) {
return { error: true, msg: (e as any).response.data.msg };
}
};
//Registrar usuario
const register = async (email: string, password: string) => {
try {
const result = await fetch(`${API_URL}/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
const json = await result.json();
console.log("registrado: ", json);
//Estado de autenticación
setAuthState({
token: json.token,
authenticated: true,
user_id: json.user.id,
});
//Guardar el token en el almacenamiento seguro
await SecureStore.setItemAsync(TOKEN_KEY, JSON.stringify(json));
return json;
} catch (e) {
return { error: true, msg: (e as any).response.data.msg };
}
};
//Cerrar sesión
const logout = async () => {
//Limpiar el almacenamiento seguro
await SecureStore.deleteItemAsync(TOKEN_KEY);
//Limpiar el estado de autenticación
setAuthState({
token: null,
authenticated: false,
user_id: null,
});
};
//hello wolrd
const hello = async () => {
//Limpiar el almacenamiento seguro
const result = await fetch(`${API_URL}/`, {
method: "GET",
});
const json = await result.json();
console.log("registrado: ", json);
return json;
};
const value = {
onRegister: register,
onLogin: login,
onLogout: logout,
authState,
initialized,
};
return {children};
};
app/index.tsx
Код: Выделить всё
import {
View,
Text,
StyleSheet,
KeyboardAvoidingView,
Platform,
TextInput,
TouchableOpacity,
Button,
Dimensions,
Alert,
} from "react-native";
import React, { useState } from "react";
import Spinner from "react-native-loading-spinner-overlay";
import Colors from "../constants/Colors";
import { useAuth } from "../context/AuthContext";
const WIDTH = Dimensions.get("window").width;
const HEIGHT = Dimensions.get("window").height;
const Page = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const { onLogin, onRegister } = useAuth();
//Función para iniciar sesión
const onSignInPress = async () => {
setLoading(true);
try {
const result = await onLogin!(email, password);
} catch (e) {
Alert.alert("Error", 'No se pudo iniciar sesión');
Alert.alert("Error", e.message);
} finally {
setLoading(false);
}
};
//Función para registrarse
const onSignUpPress = async () => {
setLoading(true);
try {
const result = await onRegister!(email, password);
} catch (e) {
Alert.alert("Error", 'No se pudo registrar');
Alert.alert("Error", e.message);
} finally {
setLoading(false);
}
};
return (
// KeyboardAvoidingView Sirve para que el teclado no tape el input
ReuMeet
La forma más rápida de reunirse
Correo electrónico
Contraseña
Iniciar sesión
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
paddingHorizontal: WIDTH > HEIGHT ? '30%' : 20,
justifyContent: "center",
},
header: {
fontSize: 30,
textAlign: "center",
marginBottom: 10,
},
subheader: {
fontSize: 18,
textAlign: "center",
marginBottom: 40,
},
inputField: {
marginVertical: 4,
height: 50,
borderWidth: 1,
borderColor: Colors.primary,
borderRadius: 4,
padding: 10,
},
button: {
marginVertical: 15,
alignItems: "center",
backgroundColor: Colors.primary,
padding: 12,
borderRadius: 4,
},
});
export default Page;
Я думаю, что есть какая-то ошибка в коде или импорте функций
Подробнее здесь: https://stackoverflow.com/questions/783 ... -undefined