I want to make a get request for each item in my renderItems() so I make it like this:
renderItems({ item }) {
axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
let eachItem = response.data;
});
console.log(eachItem);
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "flex-end",
alignSelf: "stretch",
marginRight: 2
}}
>
<Text
style={{
color: Colors.WHITE,
fontSize: 16
}}
>
{eachItem.LVal18AFC}
</Text>
</View>
);
}
But I get the error for:
ReferenceError: eachItem is not defined
I tried to convert the renderItems to an async function and use await but I get another error!
Any solution...?
I used var eachItem = [] outside the axios' then function but now I'm getting:
TypeError: Cannot read property 'LVal18AFC' of undefined!
@Jigar is correct.
Why it is not working:
When you call the renderItems function js looks at the asyn call and puts it into its event loop for execution later. It then moves on and logs to your console eachItem which is undefined right now. Then renders your JSX and then executes the async call ( i.e axios request ) when the request serves the data back it is simply store in eachItem which is in the scope of the axios function.
you did a bad practice in calling API, what I suggest is, create a separate component for each row you want to display and inside a row call an API you want
so according to your code
class Row extends Component {
constructor() {
super()
this.state = {
eachItem: null
}
}
componentDidMount() {
const { item } = this.props;
axios.get(Utilities.url + "Symbol/" + item.Id).then(response => {
this.setState({eachItem: response.data});
});
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "flex-end",
alignSelf: "stretch",
marginRight: 2
}}
>
<Text
style={{
color: Colors.WHITE,
fontSize: 16
}}
>
{this.state.eachItem ? this.state.eachItem.LVal18AFC : null}
</Text>
</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