Search code examples
javascriptreact-nativeasyncstorage

React-Native: AsyncStorage.getItem not working. I have installed AsyncStorage from react-native-community


I have a screen with buttons to select the number of players for a game. Clicking any of these buttons calls a function, passes the appropriate number into the function, stores that number in async storage, and then navigates to the next screen. See code below:

//Example of the buttons:
<Text style={styles.text}>
  How Many Players?
</Text>
<PrimaryButton
  onPress={() => this.startRound(3)}
  label="3"
>
</PrimaryButton>
<PrimaryButton
  onPress={() => this.startRound(4)}
  label="4"
>
</PrimaryButton>

//The function:
startRound = (num_players) => {
  AsyncStorage.setItem('Num_Players', num_players);
  this.props.navigation.navigate('player_names_screen');
}

On the next screen, if I try to use AsyncStorage.getItem, to get this number, so I can do things with it, I just get null. See code below:

constructor (props) {
        super(props);
        this.state = {
            get_players: null
        }
    }

    componentWillMount = () => {
        this.getNumPlayers();
        var players = this.state.get_players;
        alert(players);
    }

    getNumPlayers = async () => {
        let players = await AsyncStorage.getItem('Num_Players');
        this.setState({get_players: players});
    }

I'm using the alert function to see what I get from using AsyncStorage.getItem, and as I said before, it is showing "null". As it says in the title, I have installed async-storage from the react-native-community and am using "import AsyncStorage from '@react-native-community/async-storage';".


Solution

  • AsyncStorage can not store interger value so convert interger value into string

    AsyncStorage.setItem('Num_Players', JSON.stringify(num_players)); 
    

    Or

    AsyncStorage.setItem('Num_Players', ''+num_players); 
    

    Please check this

    https://snack.expo.io/@vishal7008/convert-variable-stored-in-asyncstorage-then-state-to-number