0
I would very much like to be able to render in a text component the value saved and changed with the Async Storage
.
In showData
I can get the new value with:
console.log(`novo valor: ${newValue}`)
but I can’t render the value on screen:
<Text>Mostrar novo valor aqui: {/* ${newValue} */}</Text>
In my attempts I obtained:
[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'
}
})
I’m starting with React Native, and I appreciate anyone who can help!
newValue
only exists in the context of the functionshowData
. Wouldn’t it be better to create a state tonewValue
(const [newValue, setNewValue] = useState('00')
), update it with Storage value at the time of calling the functionshowData
?– Cmte Cardeal