0
votes

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';".

1
Can you show the alert inside the getNumPlayers (or console.log), maybe when you show the this.state.get_players in the componentWillMount method the state isn't already updated ? - jgoday
I used this: let players = await AsyncStorage.getItem('Num_Players').then( alert(players)); And I got "undefined" in the alert. I also converted the integer value to a string when storing the value. - W. Robarts
If you use await you don't need to use 'then'. You could try let players = await ... ; alert(players) - jgoday
So it works when I have the alert inside the getNumPlayers function. But if I put the alert inside the componentWillMount, after calling getNumPlayers, I am getting "null". So I guess whatever I need to do with the number, I should just do it all in the getNumPlayers function? - W. Robarts
Check the docs of setState (reactjs.org/docs/react-component.html#setstate) specially: setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall - jgoday

1 Answers

1
votes

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