1110
1110

Reputation: 6829

What is a best way to get value from AsyncStorage before whole app load

I have App.js file and it is root of my application (both ios and android reference to it).
I have a value that I keep in AsyncStorage that I need before app.js render method is called.
Problem is that as it is async it late and I can't get that value.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.init()
  }
  async init() {
     try {
  const value = await AsyncStorage.getItem('@myPoorValue:key');
  if (value !== null){
    ...
  }
} catch (error) {}
  }
}
...
render (...

I hope that I explained good what is my issue here.
I know that there is no way to get it synchronous (I would like that) but don't know what to do in this situation.
To explain it a bit better I use I18n and I manually set I18n.locale to some value and other components get default value before I set it manually.
Just to note I also use redux and I pass selected value to it.

Upvotes: 1

Views: 4125

Answers (1)

dhorelik
dhorelik

Reputation: 1507

try the following:

...

constructor(props) {
  super(props)
  
  this state = {
    isLoading: true
  }
}
  
async componentDidMount() {
  await this.init()
  
  // you might want to do the I18N setup here
  this.setState({ 
    isLoading: false
  })
}

async init() {
    const value = await AsyncStorage.getItem('@myPoorValue:key')
    ...
}

...

the thing is that init() returns a promise and you need to wait until it gets resolved. That's when await comes to rescue.

you'll also need to set up some loader that will be there on first render, and toggle the state to replace it with actual markup after the AsyncStorage value has been fetched. I've put it in the code, but you might want to trigger a redux action instead, depending on your setup.

Upvotes: 8

Related Questions