Защищенные маршруты со страницы журнала (реагировать натив)Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Защищенные маршруты со страницы журнала (реагировать натив)

Сообщение Anonymous »

В настоящее время я разрабатываю мобильное приложение с бэкэнд с использованием Appwrite. Проблема, с которой я сталкиваюсь, заключается в том, что после успешного входа в систему и нажатия нажатию «входа в систему» ​​мне нужно перезагрузить приложение, которое будет перенаправлено на основные страницы приложения, потому что, когда экран ляплент, состояние пользователя еще не обновлено? Если да, как я могу это исправить. Любая помощь очень ценится.import { useRouter } from "expo-router"
import { useUser } from "../../hooks/useUser"
import { useEffect } from "react"
import ThemedLoader from "../ThemedLoader"

const GuestOnly = ({ children }) => {
const { user, authChecked } = useUser()
const router = useRouter()

useEffect(() => {
if (authChecked && user !== null) {
router.replace('/profilepage');
}
}, [user, authChecked])

if (!authChecked || user) {
return (

)
}

return children
}

export default GuestOnly

< /code>
Это мой файл usercontext, где я создал функцию журнала < /p>
import { createContext, useState, useEffect } from "react";
import { account } from "../lib/appwrite"
import { ID } from "react-native-appwrite"

export const UserContext = createContext();

export function UserProvider({ children }) {
const [user, setUser] = useState(null)
const [authChecked, setAuthChecked] = useState(false)

async function login(email, password) {
try {
await account.createEmailPasswordSession(email, password)
//const response = await account.get()
//setUser(response)
await getInitialUserValue()
} catch (error) {
throw Error(error.message)
}
}

async function register(email, password) {
try {
// Check if user is already logged in
const current = await account.get();

if (current) {
throw new Error("You are already logged in. Please log out before registering a new account.");
}
} catch (error) {
// If not logged in, Appwrite throws error with code 401 (unauthorized)
if (error.code !== 401) {
throw new Error(error.message);
}
}

try {
await account.create(ID.unique(), email, password);
await login(email, password);
} catch (error) {
if (error.code === 409) { // 409 is usually "Conflict" for duplicate
throw new Error("This email is already registered. Please log in or use another email.");
}
throw new Error(error.message);
}
}

async function logout() {
await account.deleteSession("current")
setUser(null)
}

async function getInitialUserValue() {
try {
const res = await account.get()
setUser(res)
} catch (error) {
setUser(null)
} finally {
setAuthChecked(true)
}
}

useEffect(() => {
getInitialUserValue()
}, [])

return (

{children}

)
}
< /code>
Это мой файл страницы входа < /p>
import { View, Text, TextInput, Pressable, StyleSheet, Keyboard, TouchableWithoutFeedback } from 'react-native';
import { useRouter } from 'expo-router';
import { useState, useEffect } from 'react';
import { useUser } from '../../hooks/useUser';

export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(null);

const { user, login } = useUser();

const handleSubmit = async () => {
setError(null);
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
setError('Please enter a valid email address.');
return;
}

try {
await login(email, password);
} catch (error) {
setError(error.message);
}
};

return (


Welcome Back






Log In



{error && {error}}


router.push('/')}>
← Back To Start


router.push('/signuppage')}>
Register Instead



);
}

const styles = StyleSheet.create({
overlay: {
flex: 1,
backgroundColor: '#FAF3DD',
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 24,
},
title: {
fontSize: 32,
fontWeight: '700',
color: '#333',
marginBottom: 28,
},
input: {
width: '100%',
borderWidth: 1,
borderColor: '#ccc',
backgroundColor: '#fff',
color: '#333',
padding: 14,
borderRadius: 10,
marginBottom: 16,
fontSize: 16,
},
button: {
backgroundColor: '#FF8C42',
padding: 14,
borderRadius: 10,
alignItems: 'center',
width: '100%',
shadowColor: '#000',
shadowOpacity: 0.15,
shadowOffset: { width: 0, height: 2 },
shadowRadius: 3,
marginBottom: 16,
},
buttonText: {
color: '#fff',
fontWeight: '600',
fontSize: 16,
},
error: {
color: '#fff',
backgroundColor: '#D9534F',
padding: 10,
borderRadius: 6,
textAlign: 'center',
},
registerButton: {
marginTop: 8,
paddingVertical: 10,
paddingHorizontal: 20,
borderColor: '#FF8C42',
borderWidth: 1,
borderRadius: 8,
backgroundColor: '#fff8f1',
},
registerText: {
color: '#FF8C42',
fontSize: 14,
fontWeight: '600',
textAlign: 'center',
},
});


Подробнее здесь: https://stackoverflow.com/questions/796 ... act-native
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Реагировать Натив. - MacOs - много проблем
    Гость » » в форуме Android
    0 Ответы
    29 Просмотры
    Последнее сообщение Гость
  • Реагировать Натив. - MacOs - много проблем
    Гость » » в форуме IOS
    0 Ответы
    35 Просмотры
    Последнее сообщение Гость
  • Беззаботно softexception - реагировать натив
    Anonymous » » в форуме Android
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • Автозаполнение OTP в iOS реагировать натив
    Anonymous » » в форуме IOS
    0 Ответы
    3 Просмотры
    Последнее сообщение Anonymous
  • FastAPI - маршруты pymongo + sync, по-видимому, НАМНОГО быстрее, чем маршруты Motor + async
    Anonymous » » в форуме Python
    0 Ответы
    31 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Javascript»