reactjsreact-nativereact-propsweather

How to pass the values from openAPIweather to a Components


I am creating a weather app using React Native. I am trying to Fetch the data of the API, so I created a file WeatherData.js that returns the name, temp and Weather.

I want to pass the data to a Component called title but this doesn't work

WeatherData.js



    return (
        <View>
            {weatherData ? (
                <View>
                    <Title
                        name={weatherData?.name}
                        temperature={weatherData?.main?.temp}
                        description={weatherData?.weather[0]?.description}
                    />
                    console.log({weatherData})
                </View>
            ) : (
                <Text>No weather data available</Text>
            )}
        </View>

    );
};

export default Data;

Title.tsx here is an example to pass the name prop

import { Text } from "react-native";
import { View, StyleSheet, StatusBar } from "react-native";


const Title = ({ name }) => {
    return (
        <View style={FontStyle.Align}>
            <Text style={FontStyle.Bold} >{name}</Text>
            <Text style={FontStyle.Thin} >Tue, Jun 30</Text>
        </View>
    );
}


export default Title;

Solution

  • Most probably the variable weatherData will be holding an empty object. An empty object is not a falsy value. Please see the expression below which evaluates to true.

    {} ? 'not falsy' : 'falsy' // not falsy
    

    Therefore the component does not return the jsx having the string "No weather data available".

    However, every reference of the properties in an empty object will yield undefined. Therefore the following expression evaluates to falsy. The Text component will ignore falsy values which will eventually give us an impression that the custom component Title does not work.

    {}.name ? 'not falsy' : 'falsy' // falsy
    

    As a solution, please diagonose and fix the reasons to get an empty object.