magic bean
magic bean

Reputation: 797

Cannot read properties of undefined (reading 'map') error when data fetching

I have companies.json and I am trying to fetch data from it and then display the company names as a checkbox, so here is my parent component:

import React, { useEffect, useState } from "react";
import SimpleBox from "../components/sub-components/SimpleBox";
import BoxWithSearch from "../components/sub-components/BoxWithSearch";
import { useDispatch, useSelector } from "react-redux";
import { listProducts } from "../actions/productActions";
import { listCompanies } from "../actions/companyActions";

export default function HomeScreen() {
  const dispatch = useDispatch();

  const companyList = useSelector((state) => state.companyList);
  const {  companies } = companyList;


  useEffect(() => {
    dispatch(listCompanies());
  }, [dispatch]);
  return (
    <div className="container">
      <div className="row">
        <div className="col-lg-3 col-md-12 col-sm-12 col-xs-12">
          <h3 className="title">Brands</h3>
          {companies.map((company) => (
            <BoxWithSearch type={"companies"} company={company} />
          ))}
        </div>
        
      </div>
    </div>
  );
}

After BoxWithSearch component:

import React from "react";
import CheckBox from "../custom-components/CheckBox";

export default function BoxWithSearch(props) {
  return (
    <div className="search-w-box card">
      <div className="card-header">
        <input type="text" className="form-control" placeholder={`Search ${props.type}`} aria-label="Recipient's username"></input>
      </div>
      <div className="card-body">
          <CheckBox text={props.name} />
      </div>
    </div>
  );
}

And here it goes to the checkbox:

import React from "react";

export default function CheckBox(props) {
  const [isChecked, setChecked] = React.useState(false);

  const toggleCheck = (e) => {
    setChecked(e.target.checked || !isChecked);
  };
  return (
    <>
      <label className="checkbox-container">
        {props.text}
        <input
          type="checkbox"
          checked={isChecked}
          onChange={(e) => toggleCheck(e)}
          id={props.id}
        />
        <span className="checkmark"></span>
      </label>
    </>
  );
}

But unfortunately, I am getting:

Uncaught TypeError: Cannot read properties of undefined (reading 'map') error and I have no idea why and it is getting me crazy.

Could you please have a look? And my JSON array is like this:

[
  {
    "slug": "Dickens-Franecki",
    "name": "Dickens - Franecki",
    "address": "12158 Randall Port",
    "city": "East Maureenbury",
    "state": "NE",
    "zip": "74529",
    "account": 31010023,
    "contact": "Lonzo Stracke"
  },
  {
    "slug": "Weissnat-Schowalter-and-Koelpin",
    "name": "Weissnat, Schowalter and Koelpin",
    "address": "92027 Murphy Cove",
    "city": "Port Malachi",
    "state": "WY",
    "zip": "56670-0684",
    "account": 81813543,
    "contact": "Kathryne Ernser"
  },
]

Upvotes: 0

Views: 3048

Answers (2)

Asif vora
Asif vora

Reputation: 3359

You can use Optional chaining (?.) to check you have data or not in the array.

Here you can check what is optional-chaining? and how it works. optional-chaining

{companies?.map((company) => (
  <BoxWithSearch 
    key={company.slug}
    type={"companies"} 
    company={company}
  />
))}

Upvotes: 3

Dawood Ahmad
Dawood Ahmad

Reputation: 474

first, check your array's (companies) value. there are no records so it shows the error, second, if the data is fetched successfully and then it shows this undefined error, you have to do:

{companies && companies.map((company) => (
        <BoxWithSearch type={"companies"} company={company} />
      ))}

by doing this you simply mean if there is data available in companies then add map()

Upvotes: 0

Related Questions