I am trying to create empty array in react-native using es6. But while accessing it I get an error data not defined.
Here is the code snippet which I am using to initialise the array.
JavaScript
x
9
1
constructor() {
2
super();
3
4
this.state = {
5
search: "",
6
data: []
7
}
8
}
9
Here is the code through which I am trying to populate the array and at the same time logging it
JavaScript
1
10
10
1
.then((responseData) => {
2
this.setState({
3
data: responseData.hits.hits.map(function(search){
4
return{
5
name: search._source.service_name
6
}
7
})
8
})
9
console.log(data);
10
I think so there is a problem in initialisation of array can anybody rectify it?
Advertisement
Answer
Your initializing of the array looks fine.
You just can’t access data
like a local scoped variable. The data
array in your example is a property/attribute of your state object.
So you need to access your data array like this:
this.state.data