How to know if constant has a value?

0

I have the code:

import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import { Tile, List, ListItem } from 'react-native-elements';

class UserDetail extends Component {
constructor(props){
  super(props);
  this.state = {
    title: '',
    phone: '',
  }
}

render() {
const { id, title, whatsapp, email, phone, login, location } = this.props.navigation.state.params;
//RECEBO A CONSTANTE ACIMA DA TELA ANTERIOR. ALGUNS ITENS VEM COM INFORMAÇÃO, OUTROS NÃO

if (title){
  this.setState({title: {title}});
}

if (phone){
  this.setState({phone: {phone}});
  //QUERO SABER SE A CONSTANTE ACIMA TEM INFORMAÇÃO, E ASSIM, USÁ-LA NO ESTADO CORRESPONDENTE, POIS QUANDO ESTÁ VAZIA DÁ ERRO
}

return (
  <ScrollView>
    <Tile
      imageSrc={{ uri: 'https://buscafree.com.br/assets/img/items/${id}.jpg'}}
      featured
      title={title}
      //caption={email}
    />

    <List>
      <ListItem
        title="Endereço"
        rightTitle={this.state.title}
        hideChevron
      />
      <ListItem
        title="Endereço"
        rightTitle={this.state.phone} //USAREI AQUI
        hideChevron
      />
    </List>
  </ScrollView>
);
}
}

export default UserDetail;

My code receives some information from the previous screen. However, not all items have a value (in my case, the PHONE item sometimes comes with information and sometimes not ...)

When I try to print it on the screen, it gives an error if it is empty / null.

How do I check if it has information before printing on the screen?

    
asked by anonymous 09.01.2018 / 13:19

1 answer

1

Just check how you're doing. But you should not use setState() in method render() - this should only have the role of model for vision, nothing else.

Then you should show a pro user interface in case the variable has no value. For example, if phone is not set, you display a message saying something like "there is no set phone value".

After the value of the variable is defined (I hope!) somehow, (eg clicks a button that makes an http request that in the end directs the state of the component) the render method will skip the "if" and go directly to the desired view.

render() {
  if (!phone) {
    return <Text>Ainda nao ha informacoes do telefone. Carregando ...</Text>;
  }

  // se phone estiver definido, mostramos a visao desejada
  return (
    {/* Visao desejada */}
  );
}

It is worth noting that you do not need to ometer the entire screen because of an undefined variable. In this case, you divide the interface into several components of learning. Each of these components checks for itself the values of the variable they need to present the information. If the value has not yet been defined, each component shows its own spinner as the load message.

    
16.01.2018 / 02:25