1

I am new to React Native, but I've started to use it to develop an app where users can upload Posts. On the Publish screen, there are two TextInput, one for the title, and another one for the body. I'd like the app to be able to save drafts in case the user closes the app, so the progress is not lost. I thought that a combination of AsyncStorage and AppState would do the job, but something is not working as it should.

export default class PublishScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            title: '',
            body: ''
        };
        this._getData();
    }

    _getData = async () => {
        await this.setState({
            'title': await AsyncStorage.getItem('title') || '',
            'body': await AsyncStorage.getItem('body') || ''
        });
    };

    componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
    }

    _handleAppStateChange = async (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
            // App is going to be in the foreground
            this._getData()
        } else {
            // App is going to be closed/background, save the data
            await AsyncStorage.setItem('title', this.state.title);
            await AsyncStorage.setItem('body', this.state.body);
        }
        this.setState({appState: nextAppState});
    };
}

This approach seems to be working in dev mode, but as soon as I build the app in release mode, the data doesn't get saved or restored, I am not really sure where it is failing.

What am I doing wrong, am I doing the feature in the right way anyway?

Dalvtor
  • 3,160
  • 3
  • 21
  • 36

0 Answers0