Home > OS >  How do I resolve Uncaught TypeError: Cannot read properties of undefined (reading 'map')?
How do I resolve Uncaught TypeError: Cannot read properties of undefined (reading 'map')?

Time:06-24

This is my code. Unable to resolve this error I am getting in the console and nothing is printed when I run the file.

import React from 'react';
import axios from 'axios';
import { Grid } from '@mui/material';
import { Box } from '@mui/material';

class TableGen extends React.Component {
  constructor() {
    super();
    this.state = {
      tableData: [],
    };
  }
  componentDidMount() {
    const res = axios
      .post(
        'https://us-central1-stockmarketcharting-8c469.cloudfunctions.net/server/performance/getbest'
      )
      .then((res) => {
        this.setState({ tableData: res.array });
      });
  }

  render() {
    return (
      <div>
        {this.state.tableData.map((row) => {
          return (
            <Grid item sm={6}>
              {row.data.price}
            </Grid>
          );
        })}
      </div>
    );
  }
}
export default TableGen;

I am getting a Cannot read properties of undefined error. Any suggestions on how to resolve this would be appreciated.

CodePudding user response:

Response of axios call comes with data object so everything you'll get is inside it like array, price, items , etc .. i would try to log res.data to the console and see the response object, there you'll find out what it contains and the required data you need :

import React from 'react';
import axios from 'axios';
import { Grid } from '@mui/material';
import { Box } from '@mui/material';

class TableGen extends React.Component {
  constructor() {
    super();
    this.state = {
      tableData: [],
      // add some flag
      isErrorFetching: false
    };
  }
  componentDidMount() {
    const res = axios
      .post(
        'https://us-central1-stockmarketcharting-8c469.cloudfunctions.net/server/performance/getbest'
      )
      .then((res) => {
        console.log("response ===>>> ", res.data);
        this.setState({ tableData: res.data });
      })
      .catch(err => {
        this.setState({ tableData: [], isErrorFetching: true });
      })
  }

  render() {
    if (isErrorFetching) {
     return <div>Something went wrong!</div>
    }
    if (!tableData.length) {
     return <div>There are no items found!</div>
    }

    return (
      <div>
        {this.state.tableData.map((row) => {
console.log("row ::: ", row);
          return (
// ensure there is a price property
            {row?.data?.price && (
             <Grid item sm={6}>
              {row.data.price}
             </Grid>
            )}
          );
        })}
      </div>
    );
  }
}
export default TableGen;

Let's assume the res.data is an array, then you cannot get the price from the item of array, then let's log the row to the console to see if it contains price or any other required data .

  • Related