Estoy codificando en react native con expo y typescript. Tengo los siguiente códigos:
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<any>; onLogin: (email: string, password: string) => Promise<any>; onLogout: () => Promise<any>; initialized: boolean;}const TOKEN_KEY = "my-stream-token";export const API_URL = process.env.EXPO_PUBLIC_SERVER_URL;const AuthContext = createContext<Partial<AuthProps>>({}); //Creamos el contexto de autenticación//Creamos el provider de autenticación que se encargará de manejar el estado de autenticaciónexport const useAuth = () => { return useContext(AuthContext);};export const AuthProvider = ({ children }: any) => { const [authState, setAuthState] = useState<{ token: string | null; authenticated: boolean | null; user_id: string | null; }>({ 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 <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;};
Y también: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<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === "ios" ? "padding" : "height"}><Spinner visible={loading} /><Text style={styles.header}>ReuMeet</Text><Text style={styles.subheader}>La forma más rápida de reunirse</Text><Text>Correo electrónico</Text><TextInput autoCapitalize="none" placeholder="Correo electrónico" value={email} onChangeText={setEmail} style={styles.inputField} /><Text style={{marginTop: 20}}>Contraseña</Text><TextInput placeholder="Contraseña" value={password} onChangeText={setPassword} secureTextEntry style={styles.inputField} /><TouchableOpacity onPress={onSignInPress} style={styles.button}><Text style={{ color: "#fff" }}>Iniciar sesión</Text></TouchableOpacity><Button title="¿No tienes una cuenta? Regístrate" onPress={onSignUpPress} color={Colors.primary} /></KeyboardAvoidingView> );};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;
Lo que sucede es que al ejecutar la aplicación y llenar los campos de correo y contraseña y dar clic en iniciar sesión me aparece el mensaje de onLogin is not a function (it is undefined) y lo mismo con onRegister.
Creo que hay algún error de código o importación de las funciones