I am mapping
json data and can console.log
my result, but I can't insert those values in the render.
Here is the code I have for my render:
data_use = responseJson;
const result_id = data_use.map(function(val) {
return val.id;
}).join(',');
console.log(result_id);
render(){
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}
The error that I am getting is ReferenceError: result_id is not defined
. Which is odd because it is defined?
This approach will be useful if the data is loaded from a server.
constructor(props) {
super(props);
this.state = {
data : []
};
}
componentDidMount() {
// Your code to fetch data from server
this.setState({ data: your_array_from_fetch });
}
render(){
return(
<View style={ styles.MainContainer }>
<View>
<Card>
<View>
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
return (
<Text key={index}>val.id</Text>
);
} ).join(',');
: null
}
</View>
</Card>
</View>
</View>
);
}
I made few assumption from my side and I believe this is what you want! If any issue write that down below.
EDIT:
componentDidMount
instead of componentWillMount
because componentWillMount
is deprecated.Try this conditional render
{
this.state.data.length > 0 ?
this.state.data.map((val, index) => {
if (some_var == another_var) {
return (
<Text key={index}>val.id</Text>
);
}
}).join(',');
: null
}
Everything you did is correct but variable you declared outside render
? How can it be accessed in render
render(){
//considering array of objects in "data_use" state
const result_id = this.state.data_use.map(function(val) {
return val.id;
}).join(',');
return(
<View style = { styles.MainContainer }>
<View>
<Card>
<View>
<Text>{result_id}</Text>
</View>
</Card>
</View>
</View>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With