Search code examples
javascriptreact-nativeasyncstorage

React Native - Using AsyncStorage to store data in another screen


I'm trying to store some data in my App using AsyncStorage, but the thing is whenever I submit the data and then navigate to the second screen (where the data should be stored) it is empty.

navigation button

SendOrder Screen

Here is my code

SendOrder.js

import Settlement from './Settlement';

export default class SendOrder extends React.Component {

state = {
    text: '',
    storedValue: '',
}

onSave = async () => {
    const { text } = this.state

    try {
        await AsyncStorage.setItem(key, text);
        Alert.alert('Saved', 'Successful');
    } catch (error) {
        Alert.alert('Error', 'There was an error.')
    }
}

onChange = (text) => {
    this.setState({ text });
}

  render() {
    return (
      <View>
        <View>
            <Text>- Noter -</Text>
        </View>
        <View>
            <TextInput
                onChangeText = {this.onChange}
                value = { this.state.text }>
            </TextInput>
        </View>
        <TouchableOpacity onPress = { this.onSave }>
            <Text style = { styles.addButtonText }> + </Text>
        </TouchableOpacity>    
      </View>
    );
  }
}

Settlement.js

import SendOrder from './SendOrder';
const key = '@MyApp:key';

export default class Settlement extends React.Component {

    state = {
        text: '',
        storedValue: '',
    }

    componentWillMount() {
        this.onLoad();
    }

    onLoad = async () => {
        try {
            const storedValue = await AsyncStorage.getItem(key);
        } catch (error) {
            Alert.alert('Error', 'There was an error.')
        }
    }

  render() {
      const { storedValue, text } = this.state;
    return (
        <View>
            <Text>{storedValue}</Text>
            <View>
                <TouchableOpacity onPress = {this.onLoad}>
                    <Text>Load Data</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
  }
}

Solution

  • You need to store the storedValue into the state inside onLoad, like

    onLoad = async () => {
        try {
            const storedValue = await AsyncStorage.getItem(key);
            this.setState({ storedValue });
        } catch (error) {
            Alert.alert('Error', 'There was an error.')
        }
    }
    

    Hope this will help!