I am calling two functions with my TouchableOpacity onPress call.
The saveList function that I am calling after my setArray function is not seeing the new item that I am adding to my state.
Therefore my new item is not being saved to my state.
The problem might be that I am calling the saveList function before the setArray function completes but I am not sure how I would do it otherwise or if there would be a better way.
The saveList function works if I call it with a separate button, however it would be more user friendly to automatically save whenever a new item is added.
import React, { useState, useContext } from 'react'
import { View, StyleSheet, Text, TextInput, TouchableOpacity } from 'react-native'
import ItemContext from '../context/ItemContext'
import { AsyncStorage } from 'react-native'
const CreateScreen = () => {
const { array, setArray } = useContext(ItemContext)
const [date, setDate] = useState()
const [amount, setAmount] = useState()
const [name, setName] = useState()
function saveList() {
_storeData = async () => {
try {
await AsyncStorage.setItem('data', JSON.stringify(array));
console.log(array)
} catch (error) {
// Error saving data
console.log(error)
}
};
_storeData()
}
return (
<View>
<View style={styles.background}>
<TextInput placeholder="Medicine/Vitamin" value={name} onChangeText={(text) => setName(text)} style={styles.input} />
</View>
<View style={styles.background}>
<TextInput placeholder="Amount" value={amount} onChangeText={(text) => setAmount(text)} style={styles.input} />
</View>
<View style={styles.background}>
<TextInput placeholder="Date" value={date} onChangeText={(text) => setDate(text)} style={styles.input} />
</View>
<TouchableOpacity onPress={() => { setArray([...array, { date: date, amount: amount, name: name, id: (array.length + 1) }]); saveList(); } } >
<View style={styles.button}>
<Text style={styles.buttonText}>Save</Text>
</View>
</TouchableOpacity>
</View>
)}