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

339 views Asked by At

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.

p.s. 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

1

There are 1 answers

4
Wen W On BEST ANSWER

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);
    }
}