Search code examples
firebasereact-nativefirebase-realtime-databasestateasyncstorage

AsyncStorage to save state with React Native


I want to save the switch button state so users can't vote twice. I have a message error : Exception '-[NSDictionaryM length...was thrown while invoking multiSet on target AsyncLocalStorage Any Idea ?

this.state= {
trueSwitchIsOn: false,
}; 

 onSwitchChange(_key){
 const{trueSwitchIsOn}=this.state;

          switch (this.state.trueSwitchIsOn){
            case false:
              return(
                <TouchableHighlight onClick={this.onPressIcon(_key)}>
                {this.setState({trueSwitchIsOn: true})}
                </TouchableHighlight>
                );
            case true:
              return(
              <TouchableHighlight onClick={this.onUnPressIcon(_key)}>
                {this.setState({trueSwitchIsOn: false})}
                </TouchableHighlight>
                );
              }
          }

onPressIcon(word){
          AsyncStorage.setItem('AlreadyLiked', {trueSwitchIsOn});
          const{trueSwitchIsOn}=this.state;
          this.setState({trueSwitchIsOn : true});
}
onUnPressIcon(word){ 
          AsyncStorage.setItem('NotAlreadyLiked', {trueSwitchIsOn: false});
          const{trueSwitchIsOn}=this.state;
          this.setState({trueSwitchIsOn : false});
<Switch>
         onValueChange={(value)=>this.onSwitchChange(_key)}
</Switch>

Solution

  • The value passed to AsyncStorage.setItem() needs to be a string. You need to either pass your object to JSON.stringify() or just use a pure string value instead of an object with a "trueSwitchIsOn" boolean property.