Nirmalya Ghosh Nirmalya Ghosh - 4 months ago 11
Javascript Question

Getting data from a JSON array and setting states based on the data using loop in React

Suppose, I'm getting JSON array and want to setState as I'm getting that array in my component.

for( var follower_id = 0; follower_id < followers_data.length; follower_id++) {
this.setState({
followers_data_username[followers_data_username.length] = followers_data[follower_id].login
});
console.log(followers_data_username[0]);
}


But I don't know how to set up my getInitialState if I'm going to use an array. Also, I don't think that I can setState of an array.

I'm new to React. So, any help or pointing to the right direction would be highly appreciated.

Consider the JSON to be something similar to this: https://api.github.com/users/ghoshnirmalya/followers

Answer

you should use a map function on your data like so

render(){
    let rows = this.state.followers_data.map( (follower, i) => <TableRow follower={follower} key={i} />);

    return (
        <table>
            <tbody>{rows}</tbody>
        </table>
    );
}

and your row component would look something like this..

const TableRow = (props) => {
    return (
        <tr>
            <td>{this.props.follower.login}</td>
        </tr>
    );
};

now this is just a basic example... you need to model it to work for your project.. but you should follow this pattern for all of the json data... you have a table and in the tbody you render rows.. which is an array of components that are generated off of each json object in the array.