2

I'm trying to fecth data from db.json dispay it in Cards. There are two objects in details array so Cards.tsx suppose to generate two SimpleCard. It's throwing this.state.card.map is not a function this error. Can anyone let me know where I made a mistake ?

SimpleCard.tsx

class ShipmentCard extends Component {
  render() {
    return (
      <Card className="Card">
        <CardContent className="Card-Content">
          <Grid container spacing={3}>
            <Grid item xs={12}>
              <h3 className="Card-Content__Title">
                title goes here
              </h3>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    );
  }
}

export default ShipmentCard;

Cards.tsx

import React, { Component } from "react";
import ShipmentCard from "../card/Card";

class Cards extends Component {
  state = {
    card: []
  };
  componentDidMount() {
    fetch("http://localhost:3001/details")
      .then(response => response.json())
      .then(data => {
        data.forEach((element: any) => {
          const shipments = element;
          this.setState({ card: shipments });
        });
      });
  }
  render() {
    return (
      <div>
        {this.state.card.map(card => (
          <ShipmentCard key={card.id} />
        ))}
      </div>
    );
  }
}

export default Cards;

App.tsx

const App: React.FC = () => {
  return (
    <React.Fragment>
      <CssBaseline />
      <TopMenu />
      <Cards />
    </React.Fragment>
  );
};

db.json

{
  "details": [
    {
      "id": "123",
      "name": "Heromisha",
      "services": [
        {
          "type": "customs"
        }
      ],
      "total": "1000",
      "status": "ACTIVE",
      "userId": "E222"
    },
    {
      "id": "456",
      "name": "Honda",
      "services": [
        {
          "type": "customs"
        },
        {
          "type": "insurance",
          "value": "100"
        }
      ],
      "total": "3000",
      "status": "ACTIVE",
      "userId": "E111"
    }
  ]
}

0

1 Answer 1

2

data seems to be the array of cards.

Try replacing

      .then(data => {
        data.forEach((element: any) => {
          const shipments = element;
          this.setState({ card: shipments });
        });
      });

by

      .then(data => this.setState({card: data}));

By the way, card seems like a strange name for the state, maybe cards would be more accurate.

Sign up to request clarification or add additional context in comments.

1 Comment

Noted that. Working good. How I missed that. Thanks @Matthieu

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.