Getting undefined is not an object in React native when rendering
You have two problems.
First, the prop you pass to RenderPhotos
is this.props.photos
, which is undefined in AwesomeProject
. Looking in the render()
function of RenderPhotos
, you try to access the element at index 0 of this.props.photos
, which is undefined. That's probably what's causing your error. I suspect you meant to set the photos prop equal to this.state.photos
in the render()
function of the AwesomeProject
component.
Second, inside componentWillMount()
of the AwesomeProject
component, you make two state changes after you get photos from the API:
this.setState({
isLoading: false
});
this.setState({
photos: JSON.stringify(responseData)
});
It's possible, but not guaranteed, that React might batch those two setState()
calls, so both state properties would be set at the same time and the render()
method would be called only once. However, if these setState()
functions are executed synchronously, the render()
function will be called while this.state.loading === false
and this.state.photos === undefined
. The RenderPhotos
component will mount and receive the prop photos={this.state.photos}
(after making the change I described above). Unfortunately, because this.state.photos
is undefined, you will encounter the same problem as above when you try to access this.props.photos[0]
inside the render()
function of RenderPhotos
. Here's my suggestion to fix your problem:
var AwesomeProject = React.createClass({
getInitialState: function() {
return {
isLoading: true,
photos: this.props.photos
};
},
componentWillMount: function(){
fetch("http://localhost:3000/api/photos/", {
method: "GET",
headers: {
"x-access-token":"xxxxx",
"x-key":"xxxx"
},
})
.then((response) => response.json())
.then((responseData) => {
AlertIOS.alert(
"GET Response",
"Search Query -> " + JSON.stringify(responseData)
)
// Set both state properties at the same time to avoid passing an undefined value as a prop to RenderPhotos
this.setState({
isLoading: false,
photos: JSON.stringify(responseData)
});
})
.done();
},
render: function() {
if(this.state.isLoading){
return <View><Text>Loading...</Text></View>
}
// RenderPhotos should receive this.state.photos as a prop, not this.props.photos
return (
<RenderPhotos photos={this.state.photos}/>
);
},
});
var RenderPhotos = React.createClass({
getInitialState: function() {
return {
photos: this.props.photos
};
},
render: function(){
var photos = Photos;
return (
<View>
<Text> {this.props.photos[0]} </Text>
</View>
)
}
});
for those who dont find solution to their problems in answers above:-
This solved my problem: I changed code from
import {React} from 'react';
to
import React from 'react';
What happened is, since React
is exported by default from the module so I cannot wrap it with curly-braces.