Ana be
Ana be

Reputation: 111

TypeError: Cannot read property 'map' of undefined in reactjs

I'm working on an app with expressjs and reactjs. I fetched the data from the backend using expressjs but I get map is not a function.

import React, { Component } from "react";
import "./products.css";
import Listofproducts from "./listofproducts";
import { Link } from "react-router-dom";

class products extends Component {
  constructor(props) {
    super(props);
    this.state = {
      productInfo: ""
    };
  }

  async getProducts() {
    try {
      const data = await fetch("http://localhost:4000/product");
      const jsonData = await data.json();
      this.setState({
        productInfo: jsonData
      });
      console.log(this.state.productInfo);
    } catch (error) {
      console.log(error);
    }
  }
  componentDidMount() {
    this.getProducts();
  }

  render() {
    return (
      <React.Fragment>
        <Listofproducts itemlists={this.state.productInfo} />
      </React.Fragment>
    );
  }
}

export default products;

Here is the component productLists where I sent the props to work with it.

import React, { Component } from "react";
import Product from "./products";

class Listofproducts extends Component {
  render() {
    const { itemslist } = this.props;
    console.log(itemslist);
    // console.log is working here i get back the data on the console
    return itemslist.map(list => {
      console.log(list);
    });
  }
}

export default Listofproducts;

Upvotes: 1

Views: 43

Answers (1)

Tholle
Tholle

Reputation: 112787

You set productInfo to an empty string in the constructor of products, and strings don't have a map method.

Change the default value to an empty array instead and it will work just as well before and after your network request completes.

class Products extends Component {
  constructor(props) {
    super(props);
    this.state = {
      productInfo: []
    };
  }

  // ...
}

Upvotes: 2

Related Questions