How to get data with AsyncStorage

0

In the first HomeCreen component, let's say that I store a string AAA , I press the save button and the text is stored using AsyncStorage. When I click browse, I go to the other component that is similar and, since I have previously stored AAA , the alert () appears with that. Now, if in this second component I do the same as in the first but I keep the string BBB , when I navigate to the previous component I should leave again the alert () with the new data.

My question is, can the component be re-created to run as if it were the first time, or can the AsyncStorage data be obtained dynamically when returning to that component? Or some way to refresh the data by navigating to that component

Code:

import React, { Component } from 'react'
        import { AsyncStorage, Button, TextInput,  View, Text, TouchableOpacity, ScrollView, FlatList, StyleSheet, Image, ImageBackground, StatusBar} from 'react-native'
        import { LinearGradient } from 'expo'
        import { createStackNavigator } from 'react-navigation'


        class ProfileScreen extends Component {

            constructor(props) {
                super(props);
                this.state = {
                    text: ''
                }
            }

            componentWillMount() {
                this.retrieveData()
            }

            saveData = async () => {
                try {
                    await AsyncStorage.setItem('MY_DATA', JSON.stringify(this.state.text))
                }catch(error) {
                        console.log(error.message)
                }
            }

            retrieveData = async () => {
                try{
                    const MY_DATA = await AsyncStorage.getItem('MY_DATA')
                    alert(MY_DATA)
                    this.setState({text: MY_DATA})
                }catch(error) {
                    console.log(error.message)
                }
            }

                navigate() {

                 console.log('navigating')
                const { navigate } = this.props.navigation;
               navigate('Home')

            }



            render() {
                return (
                    <View>
                        <TextInput style = {{width: '100%', height: 50, borderWidth: 1, marginTop: 100, backgroundColor: 'pink'}} onChangeText = {text => this.setState({text: text})}/>
                        <View style = {{width: '100%', flexDirection: 'row', justifyContent: 'space-around', marginTop: 40}}>
                            <Button title = "Save" onPress = {() => this.saveData()} />
                            <Button title = "Retrieve data" onPress = {() => this.retrieveData()} />
                        </View>
                        <Text>TEXT: {this.state.text}</Text>
                        <View style = {{width: '100%', flexDirection: 'row', justifyContent: 'space-around', marginTop: 40}}>
                            <Text onPress = {() => this.navigate()}>Navigate</Text>
                        </View>
                    </View>

                )
            }
        }


        class HomeScreen extends Component {
            static navigationOptions = {
                header: null
            }
            constructor(props) {
              super(props);
              this.toggle = this.toggle.bind(this);
              this.state = {
                  isOpen: false,
                  text: ''
              };
            }

            componentWillMount() {
                this.retrieveData()
            }


            toggle() {
                this.setState({
                  isOpen: !this.state.isOpen,
                });
            }

            updateMenuState(isOpen) {
                this.setState({ isOpen });
            }

            navigate() {

                 console.log('navigating')
                const { navigate } = this.props.navigation;
               navigate('Profile')

            }


            saveData = async () => {
                try {
                    await AsyncStorage.setItem('MY_DATA', JSON.stringify(this.state.text))
                }catch(error) {
                        console.log(error.message)
                }
            }

            retrieveData = async () => {
                try{
                    const MY_DATA = await AsyncStorage.getItem('MY_DATA')
                    alert(MY_DATA)
                    this.setState({text: MY_DATA})
                }catch(error) {
                    console.log(error.message)
                }
            }

          render() {

            return (

                <View style={styles.containerMenu}>
                    <StatusBar barStyle = 'light-content' />
                        <View style = {styles.container}>
                            <ScrollView style = {[{width: '100%', height: '100%'}]}>
                                <View>
                                    <TextInput style = {{width: '100%', height: 50, borderWidth: 1, marginTop: 100}} onChangeText = {text => this.setState({text: text})}/>
                                    <View style = {{width: '100%', flexDirection: 'row', justifyContent: 'space-around', marginTop: 40}}>
                                        <Button title = "Save" onPress = {() => this.saveData()} />
                                        <Button title = "Retrieve data" onPress = {() => this.retrieveData()} />
                                    </View>
                                    <Text>TEXT: {this.state.text}</Text>
                                    <View style = {{width: '100%', flexDirection: 'row', justifyContent: 'space-around', marginTop: 40}}>
                                    <Text onPress = {() => this.navigate()}>Navigate</Text>
                                    </View>
                                </View>
                            </ScrollView>               
                        </View>
                </View>        

            );
          }
        }

        export default class App extends Component {    
            render() {
                return (
                    <RootStack/>
                )
            }
        }

        const RootStack = createStackNavigator(
          {
            Home: {screen: HomeScreen},
            Profile: {screen: ProfileScreen},



          },
          {
            initialRouteName: 'Home',
            navigationOptions: {
              headerStyle: {
                backgroundColor: 'rgb(167,167,167)',
              },
              headerTintColor: '#fff',
              headerTitleStyle: {
                fontWeight: 'bold',
              },
              header: null
            },
          }
        );


        const styles = StyleSheet.create({
            container: {
                flex: 1,
                width: 320,
                alignItems: 'center',
                justifyContent: 'flex-start',
            },


            button: {
                position: 'absolute',
                top: 20,
                padding: 10,
            },
            caption: {
                fontSize: 20,
                fontWeight: 'bold',
                alignItems: 'center',
            },
            containerMenu: {
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: '#F5FCFF',
            },
        })
    
asked by gmarsi 19.07.2018 в 01:43
source

1 answer

1

What you need is to be able to listen to the navigation events and thus be able to execute the retrieveData method in the onWillFocus event or the onDidFocus , instead of the componentWillMount . ( reference )

    
answered by 15.08.2018 / 19:49
source