Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda