Ralph
Ralph

Reputation: 578

React native: Undefined is not an object

I'm making a react native app with expo and I'm having some trouble parsing the response data from the api. Below is a sample response from the api and my goal is to retrieve main from the weather array. I can log weather array just fine but when I put state.weather[0].main it throws the undefined object error.

Object {
  "clouds": Object {
    "all": 20,
  },
  ...,
  "weather": Array [
    Object {
      "description": "few clouds",
      "icon": "02d",
      "id": 801,
      "main": "Clouds",
    },
  ],
}

Below is my code, I fetch from the api on useEffect() hook. At first the logs shows undefined but after fetching it logs correctly except for state.weather[0].main. I just started react native coming from Android, I hope you guys could help me, I'm stuck for a day now. Thanks

const HomeScreen = ({ navigation }) => {
  const { state: { defaultCity } } = useContext(CitiesContext);
  const { state: { weather }, fetchWeather } = useContext(WeatherContext);    

  useEffect(() => {
    if (defaultCity) {
      fetchWeather(defaultCity);
    }
  }, []);

  console.log(weather);
  console.log(typeof (weather[0]));
  console.log(weather[0]);
  console.log(weather[0].main);

  return (
    <View style={styles.container}>
      <LinearGradient
        // {...weatherBgProvider[weather.weather.main]}
        colors={['#000', '#fff']}
        style={styles.gradient}
      >
        <SafeAreaView
          style={{
            position: 'relative'
          }}
          forceInset={{ top: 'always' }}
        >
          <View style={{ marginTop: Header.HEIGHT, flex: 1 }}>
            <Text >{JSON.stringify(state)}</Text>
          </View>
        </SafeAreaView>
      </LinearGradient>
    </View>
  );
};

Upvotes: 1

Views: 532

Answers (1)

behzad
behzad

Reputation: 857

If you are trying to log data in your render, you can do it like this:

<View>{This.state.weather[0] && console.log(this.state.weather[0]) }</View>

So you check it to exist before you log data Hope you get the idea and works for you

update

If your main not working, first try to parse your object into array like this:

first way use lodash (npm i --dev lodash) and import it in your project

Import _ from "lodash";

Const newdata= _.compact(Object.values(yourobject))

And then you can use newdata and i think your problem will be solved

second way use _.mapKeys(yourdata,"id") and put new data in your variable like const newdata

I hope it works

Upvotes: 1

Related Questions