Tengo una aplicación RN/Expo. El usuario puede iniciar sesión y presionar el botón del cajón (hamburguesa) y ver la información de su perfil. Esta información se extrae de un servidor de AWS, pero es realmente impredecible si la información se muestra o no. Me gustaría que se muestre todo el tiempo, pero eso nunca parece ser una garantía.
A continuación se muestra mi código:
export function DrawerContent (props){ const [ firstName, getFirstName ] = useState('') useEffect(() =>{ (async()=>{ const displayName = async () =>{ const real_response = await client_instance.get_user_info() //server function that calls user's info from the AWS server getFirstName( <Text style = {styles.title}> {real_response.first_name} {real_response.last_name} </Text> ) } displayName() } ) }, [], )... //Dentro de la declaración de devolución en el cajón, donde debe presentarse al abrir
<View style = {{marginLeft: width*0.021, flexDirection: 'column'}}> <Title style = {styles.title}>{firstName}</Title> </View>EDITAR
//This is the final form const displayName = async () =>{ const real_response = client_instance.get_user_info().then(response=>{ getFirstName( <Text style = {styles.title}> {response.first_name} {response.last_name} </Text> ) } ) console.log('response is here', real_response) }Editar para fotos:
const [ imageData, getImageData ] = useState(null) const displayPhoto = async () => { const real_response = client_instance.download_profile_photo().then(response=>{ getImageData( response.raw_data ) console.log('photo is here=>',response ) } ) } displayPhoto() <View> {imageData && <Avatar.Image source={{uri:`data:image/jpg;base64,${imageData}`}}/>} </View>Puede resolver la promesa devuelta usando entonces y llamar al método getFirstName que se encuentra dentro.
client_instance.get_user_info().then(response => { // call getFirstName here });Me pregunto si su función está siendo llamada varias veces y posiblemente sobrescribiendo el valor anterior obtenido por su función. Incluso si este no es el caso, es una buena práctica vincular solo esta información obtenida del servidor si real_response no está indefinido. También puede eliminar su matriz de dependencia no utilizada.
export function DrawerContent(props) { const [firstName, getFirstName] = useState(""); useEffect(() => { async () => { const displayName = async () => { try { const real_response = await client_instance.get_user_info(); //server function that calls user's info from the AWS server if (real_response) { getFirstName(""); } else { console.log("Could not fetch info from server."); } } catch (err) { console.log(`Error occurred fetching from server: ${err.message}`); } }; displayName(); }; }); }Si bien algunas de estas respuestas ayudaron, lo que realmente solucionó este problema fue almacenar en caché los valores después de que el usuario inició sesión inicialmente y almacenarlos para uso futuro. Además, en caso de que la respuesta inicial sea nula, el servidor seguirá intentando obtener los datos y no almacenará en caché hasta que se hayan recibido los datos.
Aquí hay un ejemplo:
El usuario se registra => El usuario inicia sesión => Información de perfil rellenada => Datos almacenados en caché
El usuario se registra => El usuario inicia sesión => La información del perfil no se completa => El servidor vuelve a verificar hasta que se recuperan los datos => Los datos se almacenan en caché