0

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> )}

  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) React state updates are asynchronous, so both state updates are queued up for *the next* render cycle. Use an `useEffect` hook to respond to the first state update. – Drew Reese May 03 '20 at 03:03
  • I got it working with a useEffect hook thank you! – StevenBelievin May 03 '20 at 03:32

0 Answers0