0

I'm trying to display data from a local API on a React.js frontend.

It's displaying a blank table with only the table headers, but no entries on the table. The JSON is coming through from the API as if I console.log(this.state.cards) it logs the arrays on the command line.

Any help is appreciated!

import React, { Component } from 'react';
import '../css/card.css';
import Card from './Card';
import CardTable from './CardTable.js';
import request from 'request';

class TopCards extends Component {

    constructor() {
        super();
        this.state = {
          cards: [],
        };
      }

    componentDidMount() {
        const url = "http://localhost:1200";
        request({
            url: url,
            json: true
        }, (error, response, body) => {
            if (!error && response.statusCode === 200) {
                for (let i in body) {
                    this.state.cards.push(body[i]);
                }
            }
        })
    }

    render() {


        if(this.state.cards) {
            var cardList = this.state.cards.map(function(card){
                return(
                    <CardTable key={card.cardName} card={card} />
                );
            });
        }

        return (
            <div className="TopCards">
                <h1>Top Cards This Week:</h1>
                <br />
                <table width="400">
                <tr>
                        <th>Name</th>
                        <th>Count</th>
                        <th>Wins</th>
                        <th>Losses</th>
                        <th>Win %</th>
                </tr>
                    {cardList}
                </table>
            </div>
        )
    }
}

export default TopCards;

1 Answer 1

1

you need to setState to notify React about the fact that you want to render something. Second, you should make sure to use immutable data strucutres. push or unshift don´t notify about any change.

for (let i in body) {
    this.setState({
        cards: [
            ...this.state.cards,
            body[i]
        ]
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply! I've changed the for (let i in body) to setState, as you did. Still no data in the table. Also console.log doesn't pass the JSON arrays through any more. Any other suggestions?

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.