Search code examples
androidreact-nativeexpoasyncstorage

React Native AsyncStorage stops working once app is offline


I have a relatively simple app (my first) that needs to display information that is retrieved from a GraphQL query and then stored in AsyncStorage. Everything works fine until you turnoff data/Wifi connections and relaunch the app - it will not load the same local data it did when networking is on. This is the same on a physical or emulated Android device.

There are no data calls except when the user initially sets their details. The app is built with version 2.7.1 of Expo & AWS Amplify. I have wasted several days with this final issue and gotten the same behaviour with Expo SecureStore & Amplify Cache and am loath to go down the route of learning and including Redux on such a simple app...

//import from react native not react
import { AsyncStorage } from 'react-native'

//calling a function as app loads
componentDidMount() {
    this._loadInitialState();
}

//retrieving String from AsyncStorage
_loadInitialState = async () => {
    try {
        const policyNum = await AsyncStorage.getItem('policyNum')
        //...
    } catch {
        //...
    }

//setting state
if (policyNum != null && policyNum != undefined) {
        this.setState({ policyNum: policyNum })
    //...
}

//the original setting of the item
setPolicyDetails = async () => {
    if (this.state.policyNum != null) {
        const policyNumber = this.state.policyNum
        this.state.policyNumSet = true
        try {
            await AsyncStorage.setItem('policyNum', policyNumber)
        } catch (err) { 
        //...
        }
    }
}

Solution

  • Are you storing a string? asyncstorage only can store strings . try using JSON.stringify and JSON.parse

    _loadInitialState = async () => {
        try {
            var policyNum = await AsyncStorage.getItem('policyNum')
            policyNum = JSON.parse(policyNum) // converting to original
            //...
        } catch {
            //...
        }
    
    //setting state
    if (policyNum != null && policyNum != undefined) {
            this.setState({ policyNum: policyNum })
        //...
    }
    
    //the original setting of the item
    setPolicyDetails = async () => {
        if (this.state.policyNum != null) {
            const policyNumber = this.state.policyNum
            this.setState({ policyNumSet: true })
            try {
                var policyNumberString = JSON.stringify(policyNumber)
                await AsyncStorage.setItem('policyNum', policyNumberString) //converting to string
            } catch (err) { 
            //...
            }
        }
    }