Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
React Native - How to set a userState, which is fetching data form a API, initial value as blank?

so, I followed a tutorial to built a weather app which fetchs data from a API. The problem is I don't want to show any data until the user type a city in ther search input. At the moment it is working fine, but it shows "undefined" as initial value when the app loads. How do I "hidden" the undefined value or how do I set it as blank?

What I'm getting as initial value

undefined, undefined, undefined
undefined
NaN°C
undefined

my code

function HomeScreen() {
  const initialValue = "zero";
  const [input, setInput] = useState('');
  const [data, setData] = useState([initialValue]);
  const [loading, setLoading] = useState(false);
  

  const api = {
    key: 'myKey',
    baseUrl: 'http://api.weatherapi.com/v1/',
  }
  const fetchDataHandle = useCallback(() => {
    setLoading(true);
    setInput("");
    axios({
      method: "GET",
      url: `http://api.weatherapi.com/v1/current.json?key=${api.key}&q=${input}&aqi=yes`,
    })
    .then(res=> {
      console.log(res.data);
      setData(res.data);
    })
    .catch(e => console.dir(e))
    .finally(() => setLoading(false));
  }, [api.key, input]);

  return (
    <View style={styles.container}>
           <View>
            <TextInput 
              placeholder='Enter city name...'
              onChangeText={text => setInput(text)}  
              value={input}
              placeholderTextColor={'black'}
              style={styles.textInput}
              onSubmitEditing={fetchDataHandle}
            />
            </View>
            {loading && (
              <View>
                <ActivityIndicator size={'large'} color="#000" />
              </View>
            )}

            {data && (
              <View style={styles.infoView}>
                <Text style={styles.cityText}>
                  {`${data?.location?.name}, ${data?.location?.region}, ${data?.location?.country}`}
                </Text>
                <Text style={styles.dateText}>{`${data?.location?.localtime}`}</Text>
                <Text style={styles.tempText}>{`${Math.round(data?.current?.temp_c)}°C`}</Text>
                <Text style={styles.conditionText}>{`${data?.current?.condition?.text}`}</Text>
                <Image style={styles.imageIcon} source={{uri: `${data?.current?.condition?.icon}`}} />
              </View>
            )}
        </View>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a feature called nullish coalescing (??). To see how it works:

const foo = null ?? "default string";
const foo1 = undefined ?? "default string";

If the value on the left side is null or undefined, the expression will return the right-side value. In this case, both foo and foo1 are "default string". In your case,

`${data?.location?.name ?? ""}`

Doing this will either display an empty string (so nothing visible) or the value of data.location.name if it is defined. This can be used in all the cases above.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda