kirimi
kirimi

Reputation: 1400

react native async getting null when running first time

I am trying to send user information to the server once the user enters their name and phone number. I was able to get the correct information when user type in their information. However, when I first run the app, I get null data for this.state.name and this.state.phone instead of empty string.

Below is my code:

constructor(){
  super()
  this.clearData = this.clearData.bind(this)
  this.persistData = this.persistData.bind(this)

  this.state = {
    name: '',
    phone: ''
  }
}

submit(){
  let collection = {}
  collection.name = this.state.name,
    collection.email = this.state.phone,
    console.warn(collection)
  var url = 'http://localhost:3000/users';
  fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(collection), // data can be `string` or {object}!
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => res.json())
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));
}

persistData(){
  let name = this.state.name
  let phone = this.state.phone
  AsyncStorage.setItem('name', name)
  AsyncStorage.setItem('phone', phone)
  this.setState({ name: name, persistedName: name, phone: phone, persistedPhone: phone })
}

check(){
  AsyncStorage.getItem('name').then((name) => {
    this.setState({ name: name, persistedName: name })
  })
  AsyncStorage.getItem('phone').then((phone) => {
    this.setState({ phone: phone, persistedPhone: phone })
  })
}

componentWillMount(){
  this.check()
}

render() {

  ////Here I am getting null! 
  console.log(this.state.name)
  console.log(this.state.phone)

  return ()
    < View >
    <TouchableOpacity
      onPress={() => { this.persistData(); this.submit(); }}>
      <Text> submit button </Text>
    </TouchableOpacity>
    </View >
}

I want to get empty string for this.state.name and this.state.phone when I first run my app.Is there a way I could do this?

Upvotes: 0

Views: 1108

Answers (1)

parohy
parohy

Reputation: 2180

AsyncStorage returns null for the value if it is not set yet. So in your situation, when you run the app first time and you call this.check() the values returned are null. Your callback overrides the default in state. After you press submit, then it is set so next time you run the app it is set.

You need to set default value in your AsyncStorage callback:

this.setState({name: name || '', persistedName: name || ''})

This sets name if it is != null and undefined else it sets the empty string.

Upvotes: 1

Related Questions