Search code examples
javascriptreact-nativeasync-awaitasyncstorage

react native Async Storage not working


I'm trying to make an auth process so my App.js:

import React, { Component } from "react";
import { AsyncStorage } from "react-native";
import Router from "./Router";
import ScanForm from "./components/ScanForm";

console.disableYellowBox = true;

class App extends Component {
  state = {
    isLoggedIn: false
  };

  componentWillMount() {   
    const temp = AsyncStorage.getItem("operator");
    console.log(temp);

    if (temp !== undefined) {
      this.setState({ isLoggedIn: true });
    }
  }

  render() {
    if (this.state.isLoggedIn) {
      return <ScanForm />;
    } else {
      return <Router />;
    }
  }
}

export default App;

So if it's the first time that user opens the app, the operator is null or undefined (i tried both but no results) - (Then in the LoginForm i will change the operator to something like "john" after the user logs in).

But it's returning the <Router /> for some reason (consider that the isLoggedIn must be false logically but...)

I've also tried to setItem in that section for testing but no results again:

componentWillMount() {
    AsyncStorage.setItem("operator", "John");

    const temp = AsyncStorage.getItem("operator");
    console.log(temp);
  }

But console.log(temp); says undefined again!

Why I can't use setItem and then fetch data with getItem?

Thanks in advance!


Solution

  • AsyncStorage is asynchronous :-). The committed value isn't available until its returned promise resolves. In exchange for this inconvenience, it won't block your JavaScript thread while the writing is underway.

    If you try:

    AsyncStorage.setItem("operator", "John").then(
       () => AsyncStorage.getItem("operator")
             .then((result)=>console.log(result))
    )
    

    You should get what you expect. (This can also be accomplished using async/await as shown in the AsyncStorage docs).

    You don't really show us how you feed props into your app, but if you update <App>'s props with isLoggedIn when the value is updated on the then, your component should update accordingly.