Iqbal Jan
Iqbal Jan

Reputation: 704

How do I assign async storage value directly to state

I need something like below but I cant get the value

state = {
  phone: async () => await AsyncStorage.getItem('phone')
}

constructor(props){
  super(props)
  alert(this.state.phone);
}

but this does not work.

I khow if call it inside componentDidMount and then pass the value to the state, it works But I need something like above.

Upvotes: 1

Views: 552

Answers (1)

Telmo Dias
Telmo Dias

Reputation: 4178

This works:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import { AsyncStorage } from 'AsyncStorage';

class App extends Component {

  state = {};

  constructor(props) {
      super(props);
  }

  componentDidMount(){
      this.getItem().then((phone)=>{
        this.setState({
          phone
        });
      })
  }

  async getItem(){
    return await AsyncStorage.getItem('phone');
  }

  async setItem(){
    await AsyncStorage.setItem('phone','919303580');
  }

  render() {
    return (
      <div className="App">
        <p>Phone here:</p>
        {this.state.phone && <p>{this.state.phone}</p>}
        <button onClick={this.setItem.bind(this)}>Click me</button>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Related Questions