Gostaria muito de conseguir estar renderizando em um componente de texto o valor salvo e alterado com o Async Storage
.
Em showData
eu consigo obter o novo valor com:
console.log(`novo valor: ${newValue}`)
porém não consigo renderizar o valor em tela em:
<Text>Mostrar novo valor aqui: {/* ${newValue} */}</Text>
Em minhas tentativas obtive:
[Fri Jan 15 2021 22:05:33.510]ERROR ReferenceError: Can't find variable: newValue
import React, { useState } from 'react'
import {
View,
Text,
StyleSheet,
TouchableOpacity,
TextInput,
Alert
} from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
export default function Home() {
const [value, setValue] = useState('00')
const saveData = async () => {
var newValue = value
await AsyncStorage.setItem('newValue', JSON.stringify(newValue))
Alert.alert('Dados salvos com sucesso!')
}
const showData = async () => {
var json = await AsyncStorage.getItem('newValue')
var newValue = JSON.parse(json)
console.log(
`novo valor: ${newValue}`
)
}
return (
<View style={styles.container}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text>Alterar valor: </Text>
<TextInput value={value}
onChangeText={text => setValue(text)} />
<Text>Mostrar novo valor aqui: {/* ${newValue} */}</Text>
</View>
<TouchableOpacity onPress={saveData}>
<Text>Salvar</Text>
</TouchableOpacity>
<TouchableOpacity onPress={showData}>
<Text>Mostrar</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFF',
alignItems: 'center',
justifyContent: 'center'
}
})
Estou começando com React Native, agradeço quem puder ajudar!
newValue
so existe dentor do contexto da funcaoshowData
. Nao seria melhor criar um estado paranewValue
(const [newValue, setNewValue] = useState('00')
), atualizar ele com valor do storage na hora da chamar a funcaoshowData
? – Cmte Cardeal 16/01 às 2:07