Search code examples
androidiosreact-nativeasyncstorage

how to save and update the application after changing to asyncstorage


render(){
const { navigate } = this.props.navigation;
if (this.state.isRefreshing) {
  return(
    <Spinner/>
  )
}
return(
  <Container style={style.container}>
    <Content>
      <List dataArray={this.state.list} renderRow={(data) =>
        <ListItem>
          <CheckBox onPress={() => this.saveLang(data.code)} checked={data.checked} />
            <Text style={style.black}> {data.title}</Text>
        </ListItem>
      }/>
    </Content>
  </Container>
)}

After saving how to update the state and apply the selected language

saveLang(value){
AsyncStorage.setItem("language", value);
this.setState(
  {
    list: [
    {
      'code': 'ru',
      'title': 'Русский',
      'checked': value == 'ru'
    },
    {
      'code': 'en',
      'title': 'English  ',
      'checked': value == 'en'
    }
  ],
  isRefreshing: true,
  }
);
I18n.locale = value;}

refresh passes, but I do not know how to update the application in the background mode enter image description here


Solution

  • It's hard to say without knowing more about what you want to happen, but AsyncStorage.setItem returns a Promise so if you need to do something after it has completed, just use then:

    function saveLang(value) {
      AsyncStorage.setItem("language", value).then(() => {
        // Perform your refresh
      });
    }
    

    Or alternatively, use async/await syntax:

    async function saveLang(value) {
      await AsyncStorage.setItem("language", value);
      // Perform your refresh
    }