After using the setItem method value of 'name' variable should change to value entered in the textInput but console.log(item) shows 'loading' After clicking submit button at first time. Which is initial value of the 'name' variable in useState.
Once I entered the submit button again the name variable value change to value entered in textInput.
Expected: When I click submit button at first time, item.name variable should change to textInput value
Using same code in class component work fine.
export default function App() {
const arr =[]
const [text, setText] = useState()
const[item,setItem] = useState([
{name: 'loading'}
])
const storedata= async ()=> {
// setItem({name: text})
arr.push({name: text})
try {
await AsyncStorage.setItem('mykey',JSON.stringify(arr));
console.log(await AsyncStorage.getItem('mykey'))
}
catch (error) {
console.log(error)
}
try{
setItem({item: JSON.parse(await AsyncStorage.getItem('mykey'))})
console.log('printing item',item)
}
catch(e){
console.log(e)
}
}
return (
<View style={styles.container}>
<TextInput onChangeText={(text) => setText(text)}
placeholder='type'
/>
<Button title='change'
onPress={storedata}
/>
</View>
);
}
Output: Button click first time: printing item [{"name":"loading"}]
Button click second time: printing item {"item":[{"name":"hi"}]}
class App extends React.Component{
arr=[]
id=0
state= {
text: '',
item:[
{name: 'loading'}
]
}
storedata = async () => {
this.arr.push({ name: this.state.text})
await AsyncStorage.setItem('mylist',JSON.stringify(this.arr));
this.setState({
item: JSON.parse(await AsyncStorage.getItem('mylist'))
})
console.log(item)
}