1

i'm having a little trouble with a for loop. This program gathers data from my back end, and is supposed to loop through the data. But, the loop is only displaying 1 _id, and console.logging two 10's. I appreciate the help in advanced, and all tips / criticism is appreciated.

**The problem seems to be in the i++... if i log I every time, it stays as 0!

import React, { Component } from 'react';
import getTransactions from '../api/TransactionAPI';

export class Dashboard extends Component {

state = {
    transactions: ""
}

componentDidMount() {
    getTransactions().then(res => {
        this.setState({ transactions: res.data });
      }).catch(error => {
        console.log(error)
      });
}

mapData(data) {
    for (let i = 0; i < data.length; i++) {
        console.log(data.length);
        return <h1>{data[i]._id}</h1>
    }
}

render() {
    if (this.state.transactions === "") {
        return (
            <p>loading...</p>
        )
    } else {
        return (
            <div>
                { this.mapData(this.state.transactions) }
            </div>
        )
    }
}

}

export default Dashboard;
0

1 Answer 1

1

You aren't returning anything from mapData. Try

mapData(data) {
   const elements = [];
   for (let i = 0; i < data.length; i++) {
       console.log(data.length);
       elements.push(<h1>{data[i]._id}</h1>)
   }

   return elements;
}

Additionally, instead of a for loop, (making some assumptions about your data) you can use .map instead.

mapData(data) {
    return data.map(d => (
        <h1>{d._id}</hi>
    ))
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.