0
votes

I am working on my first React Native app. I am trying to learn how AsyncStorage works, but I somehow can't make it work even though it is said to be simple.

I am trying to save the data to storage, whenever the store is updated. The problem is that the code below the line: "await AsyncStorage.setItem("TODOS", jTodo)" does not seem to run. I don't know what the problem is...

const unsubscribe = store.subscribe(save);

async function save(){
  try {
    const todos = store.getState().todos
    console.log(todos)
    const jTodo = JSON.stringify(todos)
    await AsyncStorage.setItem("TODOS", jTodo)
    console.log("saving 2: " + todos);

  } catch (e) {
    console.error('Failed to save todos.' + todos)
  }
}

The same is the case when I try to load data from storage. Again the code below the line: "const jTodos = await AsyncStorage.getItem('TODOS')" does not seem to run.

async function load() {
  try {
      console.log("so far even better")
      const jTodos = await AsyncStorage.getItem('TODOS')
      const todos = JSON.parse(jTodos);
      console.log(todos);
      todos.map((todo) => this.props.addTodo(todo))   
  } catch (e) {
      console.error('Failed to load todos.')
  }
}

load();

I hope some of you can point out what the problem is! Thank you in advance!!

1
did you get any error ?ashutosh pandey
No I don't get an error either. But whenever I reload my app I don't have any data, so I assume it isn't correctly saved and/or loaded...Sofie Westphal Pedersen

1 Answers

1
votes

If you are using android there is known issues with it not working. "cold boot" your emulator from android studio.

https://github.com/facebook/react-native/issues/14101