javascript – TypeError: Cannot read properties of undefined (reading ‘map’) in react redux – Stack Overflow

How can i solve this issue ? typeerror: cannot read properties of undefined (reading ‘map’) in react.js

It seems you have mixed up which version of react-bootstrap you are using. The Accordion component API changed between v1 (Bootstrap 4.6) and v2 (Bootstrap 5.1).

Here with react-bootstrap v1.6.4 your code works without issue.

Edit how-can-i-solve-this-issue-typeerror-cannot-read-properties-of-undefined-rea

V1 Accordion API

This version has the Accordion, Accordion.Toggle, and Accordion.Collapse components.

V2 Accordion API

The v2 version has a few more options with Accordion, Accordion.Item, Accordion.Header, Accordion.Body, Accordion.Button, and Accordion.Collapse.

I suggest sticking to v1.6.4 and keeping your existing code working. If you want, or need, to upgrade then it’s a bit unclear what immediate component changes you’ll need to have a similarly working UI/UX, though I suspect the new accordion components will replace some of the card components currently used.

You can use either named or default export of the notes though, just don’t use the module.exports.

Issue

The JSON response is already an array.

let json = await response.json();

React-chart2: cannot read properties of undefined (reading ‘map’)

compare your code with this working example and see what went wrong.

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
import faker from 'faker';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'Chart.js Bar Chart',
    },
  },
};

const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

export const data = {
  labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
    },
    {
      label: 'Dataset 2',
      data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
      backgroundColor: 'rgba(53, 162, 235, 0.5)',
    },
  ],
};

export function App() {
  return <Bar options={options} data={data} />;
}

demo

Читайте также:  Сбербанк аст плагин недоступен: ошибка при открытии хранилища, error internet explorer 11, содержимое подписи пустое, sberbank ast скачать, не установлен, доступ к ресурсу запрещен, истекло время ожидания загрузки - Банк и инвестиции

pay attention that all the examples of react-chartjs-2 written in Typescript so if you are working with jsx not tsx files you may need to check this question:

How do I convert TSX to JSX

Solution

Just dispatch the action with the json JSON data value:

dispatch(cartoons_are_loaded(json))

Full code:

Typeerror: cannot read properties of undefined (reading ‘map’) – state returns undefined

I am trying to retrieve a array inside a state, then go for a map, but returns undefined. It seems the state is not ready but have no idea why.

I tried a lot of alternatives but even the length I cannot get, it also returns undefined. Only the data in function getProductDetails I can get length, no other place. So this is why I think is something related to the state readiness, but no idea how to solve.

Any help would be appreciated.

import React, { Component } from 'react';
import propTypes from 'prop-types';
import { Link } from 'react-router-dom';
import cartIcon from '../images/cartIcon.jpg';
import backIcon from '../images/backIcon.jpg';
import '../styles/ProductDetails.css';

export default class ProductDetails extends Component {
  constructor() {
    super();
    this.state = {
      product: {},
    };
  }

  componentDidMount() {
    this.getDetails();
  }

  async getProductDetails(item) {
    const url = `https://api.mercadolibre.com/items/${item}`;
    const response = await fetch(url);
    const data = await response.json();
    return data;
  }

  async getDetails() {
    const { match: { params: { id } } } = this.props;
    const product = await this.getProductDetails(id);
    this.setState({
      product,
    });
  }

  render() {
    const { product } = this.state;

    return (
      <section className="details">
        <div className="details__header">
          <div className="details__back">
            <Link
              to="/"
              className="back__btn"
              data-testid="shopping-back-button"
            >
              <img
                id="back-button"
                name="back-button"
                alt="Voltar"
                src={ backIcon }
                className="back__img"
              />
            </Link>
          </div>
          <div className="details__cart">
            <Link
              to="/carrinho-de-compras"
              className="cart__btn"
              data-testid="shopping-cart-button"
            >
              <img
                id="cart-button"
                name="cart-button"
                alt="Carrinho de Compras"
                src={ cartIcon }
                className="cart__img"
              />
            </Link>
          </div>
        </div>
        <div className="details__product">
          <div className="details__left">
            <p data-testid="product-detail-name">{ product.title }</p>
            <img src={ product.thumbnail } alt={ product.title } />
            <p>{ product.id }</p>
            <p>{ product.price }</p>
          </div>
          <div className="details__right">
            <ul>
              {(product.attributes)
                .map(({ name, value_name: valueName }, index) => (
                  <li key={ index }>
                    {name}
                    :
                    {valueName}
                  </li>))}
            </ul>
          </div>
        </div>
      </section>
    );
  }
}

ProductDetails.propTypes = {
  match: propTypes.shape({
    params: propTypes.shape({
      id: propTypes.string,
    }),
  }).isRequired,
};

Typeerror: cannot read properties of undefined (reading ‘map’) in react redux

I am trying to create a simple web application which lists products from fakestore api using REACT REDUX. But react is throwing the error “TypeError: Cannot read properties of undefined (reading ‘map’)”.

Читайте также:  Подача документов на государственную регистрацию в электронном виде

productListing.jsx

The above component is responsible for api call from fakestoreapi and updating the redux store.

In the following component named “productComponent.jsx” i tried to list the products from the redux store using map method which is as follows :

But React is throwing the folowing error :
Error Image

when i consoled the products object it shows undefined. But after I commented renderlist and again consoled the products object it consoled two time with the first one being undefined and second one printing the correct object with values. At this point of time I uncommented the render list, now the react is listing the products but when i again reload the page it consoles undefined value for two times.

Typeerror: cannot read properties of undefined (reading ‘map’) react

The error is that for some reason, props.tvshows is undefined within TvList, even though it should be passed down from App to TvPage to TvList. At some point down the line, tvshows is lost.

I would suggest logging all instances of tvshows, starting from when it is first defined in App, then logging in TvPage, then TvList, to see where exactly the problem is coming from. Once you’ve found it, do some debugging to make the problem stop.

Оцените статью
ЭЦП Эксперт
Добавить комментарий

Adblock
detector