NickP
NickP

Reputation: 1414

Hide state driven text until state is ready

In my application, I have different components driven by the current text in state. E.g.:

<Text>Account Balance: {this.state.account_balance}</Text>

However, wondering what is best practice to only show these once the state is set (currently waiting on an axios call)?

My hacky solution is to set a 'show' state that controls some logic. But this feels long winded and suspect their may be more simple ways to handle this.

Upvotes: 1

Views: 27

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85132

Assuming the account balance starts off as something like null to indicate it's not loaded yet, you can simply check for that before you render the <Text> element. For example:

state = {
  account_balance: null,
}

async componentDidMount() {
  const response = await fetch('someUrl');
  const data = await response.json();
  this.setState({
    account_balance: data
  });
}

render () {
  return (
    <View>
      {this.state.account_balance !== null && 
        <Text>Account Balance: {this.state.account_balance}</Text>
      }
    </View>
  )
}

Upvotes: 3

Related Questions