i-Square Innovations i-Square Innovations - 1 month ago 13
React JSX Question

How to loop through an array of data in React-native?

map function is used but it returns endless loop on console.log and i cannot render the rows in return jsx also tried the foreach but its no help. cannot render the data in jsx. its possible to console .log the data even inside the the loop . but not on the render jsx.

import React, { Component } from 'react';
import { TouchableOpacity,DrawerLayoutAndroid,Picker,ListView } from 'react-native';
import { Container, Header, Title, Content,List, ListItem, Text, Button, Icon,InputGroup, Input,View } from 'native-base';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { Actions } from 'react-native-router-flux';
import axios from 'axios';
import styles from '../styles/homestyle';
export default class Home extends Component {

constructor(props) {

super(props);

this.state = {
user_namez : "",
user_pazz : "",
};
}
student_data(){

axios.get('http://192.168.0.108/easy_backend/app/app_db/stud_data')

.then((response) => {

let respdata = response.data ;

list.respdata(function(y){

return(<Text>{y.prnt_usernamez}</Text>);

});

});

}

render() {

return (

<View>

{this.student_data()}

</View>
)

}



}

Answer

student_data() doesn't return anything. So nothing will never render from student_data().

For asyncronous calls, you must use componentDidMount().

  • add a node response: [], in Home state,
  • fill it in a componentDidMount() function
  • Then loop on this.state.response in the render() method

Something like:

    export default class Home extends Component {
        constructor(props) {
            super(props);

            this.state = {
                response: [],
                user_namez: "",
                user_pazz: "",
            };
        }

        componentDidMount() {
            axios.get('http://192.168.0.108/easy_backend/app/app_db/stud_data')
            .then((response) => {
                //as soon as the state is updated, component will render using updated values
                this.setState({ response: response});
            });
        }

        render() {
            return (
                <View>
                    {
                        this.state.response.map((y) => {
                            return (<Text>{y.prnt_usernamez}</Text>);
                        })
                    }
                </View>
            );
        }
    }