简体   繁体   中英

Save a single string in React Native iOS and Android expo app

I have tried using Async Storage but clearly I am missing something - if anyone can help with that it would be appreciated.

saveLevel = async () => {
    try {
      let levelToSave = String(this.state.level);
      await AsyncStorage.setItem("level", levelToSave);
    } catch (err) {
      console.log(err);
    }
  };

I call this function from a callback of setState({}, ()=> {here()})

However, I only need persistent storage for 1 single string. I thought of using fs.readFile but this is not available in React.

Surely there is a small hack way to save this string in a persistent way. Thanks.

ps I don't mind an ugly way of achieving this.

componentDidMount() {
    let getLevelAsync = this.getLevel();
    console.log(getLevelAsync)

*logs*

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}
getLevel = async () => {
    try {
      let level = await AsyncStorage.getItem("level");
      console.log(level, 'trying to get level')
      if (level !== null) {
        return level;
      }
    } catch (err) {
      console.log(err, 'no get worky');
    }
  };

getLevel is called in the didMount() function

are you getting the stored string from the storage?

const str = await AsyncStorage.getItem("level");

In order to make it persistent, you will need to get it from the storage and set it to the initial value of the state variable.

edits:

Try the following in componentDidMount();

componentDidMount(){
    this.getLevel().then((level)=>{
       console.log('level =', level);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM