How to Read React Errors (fix ‘Cannot read property of undefined’!)

Uncaught typeerror: cannot read property — что это означает – журнал «код» программирование без снобизма

Допустим, вы делаете страницу с формой и полем ввода:

<form name="myform">
<input name="myinput" value="10" />

Нужно, чтобы скрипт нашёл эту форму, достал из неё значение поля ввода и вывел его на экран. Вы пишете скрипт и оформляете его как отдельный файл, который подключаете в разделе head:

var str = '';
for(i=0; i < document.myform.elements.length; i ){
str = document.myform.elements[i].name
'=' encodeURIComponent(document.myform.elements[i].value)
(i == document.myform.elements.length -1 ? '' : '&');

Этот скрипт должен быть правильным. При тестировании внутри консоли он делает именно то, что нужно. Но после запуска скрипт падает с ошибкой:

❌ Uncaught TypeError: Cannot read property

Это означает: «Вы пытаетесь прочитать у объекта какое-то свойство, но я не могу его найти, а значит, не могу и прочитать то, чего нет».

Странно, ведь вы уверены, что у этого объекта такое свойство точно есть, и вы сто раз так уже делали.

Всё так и одновременно не так.

Эта ошибка чаще всего происходит, когда вы обращаетесь к свойствам объекта раньше, чем объект готов:

  • Скорее всего, объект ещё не загрузился.
  • Может быть, этот объект должен появиться на странице по скрипту, который ещё не выполнился.
  • Допущена опечатка в названии объекта, поэтому при обращении к нему скрипт его не находит.

Наш случай — первый и самый распространённый: мы вызываем скрипт в разделе <head>, но форма у нас ещё не готова — она банально не загружена в документ, поэтому скрипт не может прочитать свойства несуществующей формы.

Чтобы избавиться от этой ошибки, нужно добавить в вызов скрипта атрибут defer — он заставит скрипт подождать, пока страница загрузится полностью, вместе с формой.

<script defer src="...">

Второй вариант — поместить вызов скрипта сразу после формы, тогда к моменту вызова всё окажется на своих местах и ошибки не будет. Или вообще в конце всего документа.

Fixing this in the real world

Of course this example is tiny and contrived, with a simple mistake, and it’s colocated very close to the site of the error. These ones are the easiest to fix!

There are a ton of potential causes for an error like this, though.

Maybe items is a prop passed in from the parent component – and you forgot to pass it down.

Or maybe you did pass that prop, but the value being passed in is actually undefined or null.

If it’s a local state variable, maybe you’re initializing the state as undefined – useState(), written like that with no arguments, will do exactly this!

If it’s a prop coming from Redux, maybe your mapStateToProps is missing the value, or has a typo.

Whatever the case, though, the process is the same: start where the error is and work backwards, verifying your assumptions at each point the variable is used. Throw in some console.logs or use the debugger to inspect the intermediate values and figure out why it’s undefined.

You’ll get it fixed! Good luck 🙂

Follow the clues: how to diagnose the error

So the stack trace told us where to look: line 9 of App.js. Let’s open that up.

Here’s the full text of that file:

Line 9 is this one:

Читайте также:  Доверенность на пользование ЭЦП от директора или руководителя — образец

And just for reference, here’s that error message again:

Let’s break this down!

  • TypeError is the kind of error

There are a handful of built-in error types. MDN says TypeError “represents an error that occurs when a variable or parameter is not of a valid type.” (this part is, IMO, the least useful part of the error message)

  • Cannot read property means the code was trying to read a property.

This is a good clue! There are only a few ways to read properties in JavaScript.

The most common is probably the . operator.

How to find the error

First order of business is to figure out where the error is.

If you’re using Create React App, it probably threw up a screen like this:

Look for the file and the line number first.

How to read the stack trace

If you’re looking at the browser console instead, you’ll need to read the stack trace to figure out where the error was.

These always look long and intimidating, but the trick is that usually you can ignore most of it!

The lines are in order of execution, with the most recent first.

Here’s the stack trace for this error, with the only important lines highlighted:

I wasn’t kidding when I said you could ignore most of it! The first 2 lines are all we care about here.

The first line is the error message, and every line after that spells out the unwound stack of function calls that led to it.

Let’s decode a couple of these lines:

Here we have:

  • App is the name of our component function
  • App.js is the file where it appears
  • 9 is the line of that file where the error occurred

Let’s look at another one:

  • performSyncWorkOnRoot is the name of the function where this happened
  • react-dom.development.js is the file
  • 15008 is the line number (it’s a big file!)

Ignore files that aren’t yours

I already mentioned this but I wanted to state it explictly: when you’re looking at a stack trace, you can almost always ignore any lines that refer to files that are outside your codebase, like ones from a library.

Usually, that means you’ll pay attention to only the first few lines.

Scan down the list until it starts to veer into file names you don’t recognize.

There are some cases where you do care about the full stack, but they’re few and far between, in my experience. Things like… if you suspect a bug in the library you’re using, or if you think some erroneous input is making its way into library code and blowing up.

The vast majority of the time, though, the bug will be in your own code 😉

The quick fix

This error usually means you’re trying to use .map on an array, but that array isn’t defined yet.

That’s often because the array is a piece of undefined state or an undefined prop.

Make sure to initialize the state properly. That means if it will eventually be an array, use useState([]) instead of something like useState() or useState(null).

Let’s look at how we can interpret an error message and track down where it happened and why.

Читайте также:  Результаты проверки эцп

Typeerror: cannot read properties of undefined (reading ‘id’) when trying to delete an entry

I can’t seem to delete a record on firebase that has been assign to a user uid, like an object inside an object.

  <v-container id="tutorials">
      <h1>Gigs Available!</h1>
           <!-- loop over the tutorials -->
           <div  class="Agrid d-grid">
           class="Amodule  back"
           v-for="gig in allGigs"
           <div class="fill-height">
             <v-container >
              <a @click.prevent="deleteGigs(gig)" class="card-link">
                 <v-icon color=red>mdi-delete</v-icon>
             <div class="d-flex align-start">
               <h3 class="j-title center mb-00">{{ gig.gigtitle}}</h3>
             <h6 class="">{{gig.companyname}}</h6>
             <v-row class="d-flex ">
               <p class="col-tres mdi mdi-clock text--secondary"> {{ gig.vacanttype }} </p>
               <p class="col-tres mdi mdi-earth text--secondary"> {{ gig.giglocation }} </p>
               <p class="col-tres mdi mdi-calendar text--secondary">{{gig.gigdate}} </p>
             <v-divider class="mx-4"></v-divider>
             <h5 class="left text-body-2">Company description</h5><br>
             <p class="content"> {{ gig.companydescription}}</p><br>
             <h5 class="left text-body-2">Gig description</h5><br>
             <p class="content"> {{ gig.gigdescription}}</p><br>
             <h5 class="left text-body-2">Gig benefits</h5><br>
             <p class="content"> {{ gig.gigbenefits}}</p><br>
             <h5 class="left text-body-2">Skills</h5><br>
             <p class="content"> {{ gig.gigskills}}</p><br>

import nativeToast from 'native-toast'
import firebase from '@/plugins/firebase'
let db = firebase.database();
//let usersRef = db.ref('users');
let gigRef = db.ref('gigs');

export default {
  name: 'EditGigs',
  data: () => ({
  authUser: null,
  allGigs: [], // initialise an array
  methods: {
       deleteGigs(gig) {
  created: function() {
    //data => console.log(data.user, data.credential.accessToken)
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
          gigRef.child(user.uid).on('child_added', snapshot => {
              this.allGigs.push({...snapshot.val(), id: snapshot.key
              if (snapshot.val().user !== this.authUser) {
                      message: `New message by ${snapshot.val().authUser}`,
                      type: 'success'
          gigRef.child(user.uid).on('child_removed', snapshot => {
              const deleteGigs = this.allGigs.find(gig => === snapshot.key)
              const index = this.allGigs.indexOf(deleteGigs)
              this.allGigs.splice(index, 1)
              if (snapshot.val().user !== this.authUser) {
                      message: `Gig deleted by ${snapshot.val().authUser}`,
                      type: 'warning'

The error looks like this:

Console log error saying TypeError: Cannot read properties of undefined (reading ‘id’)

Here is how the data looks in firebase:

-MjxHR5FjvNgB_cvp5Q3: {companydescription: 'nudream is a startup that creates applicacionts fo…siness and upgrades current apps from businesses ', companyname: 'NuDream', gigbenefits: 'Full paid, contract imss, schema mixto alot of benefits, with alot of things ', gigdate: '2021-09-19', gigdescription: 'we are actively looking for an ongoing poisition with strong front end skills!', …}
-MjxUCHolM-AW9pHL_gz: {companydescription: 'Canopy is developing innovative software to suppor… works, what doesn’t, and what could be improved.', companyname: 'Canopy', gigbenefits: 'Competitive salary with opportunities for performa… professional tools you need to do your best work', gigdate: '2021-09-22', gigdescription: 'Our team is growing! We’re seeking to fill several…ur software engineering and client success teams.', …}
-MjxUPZRLRhZ5xglpNAN: {companydescription: 'At GovExec, our mission is to inform and inspire g… in their work and make the world a better place.', companyname: 'Canopy', gigbenefits: 'Competitive salary with opportunities for performa… professional tools you need to do your best work', gigdate: '2021-09-19', gigdescription: 'As the market-leading information platform, for ov…remote work can be accommodated in select states.', …}
-Mjy4Hv3G18t1lZvI2Eq: {companydescription: 'This is the company description, we will see this in a second!', companyname: 'Gigmasters', gigbenefits: 'Lots of benefits!', gigdate: '2021-09-19', gigdescription: 'This is the Gig description!', …}
-Mjy9aKhAPNxNnWriF8K: {companydescription: 'As the market-leading information platform, for ov…s federal, defense, and state and local agencies.', companyname: 'NuStuff', gigbenefits: 'All you want!', gigdate: '2021-09-19', gigdescription: 'As the market-leading information platform, for ov…s federal, defense, and state and local agencies.', …}
-MjzJDQBvPcPgyoLahxN: {companydescription: 'esta es mi company description ', companyname: 'Nudream', gigbenefits: 'alll you want   incentives', gigdate: '2021-09-19', gigdescription: 'esta es mi description de gig ', …}
-Mk0OihUYZv8tQjnb7MS: {companydescription: ' adas dad aas das dasd ', companyname: 'a da da dad asd as d', gigbenefits: ' ada d sadsa dsad sad', gigdate: '2021-09-19', gigdescription: 'a da sdas das d ad sa', …}
[[Prototype]]: Object

This is how the data is being pushed in a separate child component form:

methods: {
        addGig: function() {
            this.newGig.vacanttype = '';
            this.newGig.gigtitle = '';
            this.newGig.gigdescription = '';
            this.newGig.companyname = '';
            this.newGig.companydescription = '';
            this.newGig.giglocation = '';
            this.newGig.gigdate = '';
            this.newGig.gigbenefits = '';
            this.newGig.gigskills = '';
            this.newGig.priority = '';
            toastr.success('Horray! message sent successfully');
            this.displayText = 'Nice job!';
            this.vacanttypeRules = true;
            this.gigtitleRules = true;
            this.gigdescriptionRules = true;
            this.companynameRules = true;
            this.companydescriptionRules = true;
            this.gigskillsRules = true;
            this.gigbenefitsRules = true;
            this.giglocationRules = true;
            this.priorityRules = true;

What I am trying to do:

Читайте также:  "С уважением" и еще 29 способов подписать письмо | MediaDigger

Ui look for better understanding I want to delete each object on click

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

I am trying to use bootstrap modal to display each item on a table when clicked on the view button.
I initially did it in a single file and it’s but now I tried to separate the modal from the list of items both which means I have two files for them now and I am getting this error: TypeError: Cannot read properties of undefined (reading ‘name’)

Below is my code:

import React, {useState} from 'react';
import { Table } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { DetailModal } from './DetailModal';

const ModalPractice = () => {
  const [show, setShow] = useState(false);

  const [selectedItem, setSelectedItem] = useState({});

  const handleClose = () => {

  const handleShow = (e, item) => {

  const food = [
      id: 1,
      name: 'rice',
      category: 'grain',
      image: 'images/rice.jpg',
      id: 2,
      name: 'beans',
      category: 'grain and protein',
      image: 'images/beans.jpg',
      id: 3,
      name: 'amala',
      category: 'swallow',
      image: 'images/amala.jpg',
      id: 4,
      name: 'Oat',
      category: 'cereals',
      image: 'images/oat.jpg',
      id: 5,
      name: 'coke',
      category: 'soft drink',
      image: 'images/coke.jpg',
      id: 6,
      name: 'banana',
      category: 'fruit',
      image: 'images/banana.jpg',
      id: 7,
      name: 'okra',
      category: 'vegetable',
      image: 'images/okra.jpg',
      id: 8,
      name: 'yam',
      category: 'tuber',
      image: 'images/yam.jpg',
      id: 9,
      name: 'palm oil',
      category: 'fat',
      image: 'images/palmoil.jpg',
      id: 10,
      name: 'orange',
      category: 'fruit',
      image: 'images/orange.jpg',

  return (
      {/* <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Button variant='secondary' onClick={handleClose}>
          <Button variant='primary' onClick={handleClose}>
            Save Changes
      </Modal> */}

      <Table striped bordered hover>
            <th>Food Name</th>
            <th>Food Category</th>
          { => (
            <tr className='align-middle' key={}>
                <img alt='' src={list.image} width='100' height='100' />

export default ModalPractice;


import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Button, Modal } from 'react-bootstrap';

export const DetailModal = (props) => {
  const {selectedItem, show, handleClose, handleShow, list} = props
  return (
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Button variant='secondary' onClick={handleClose}>
          <Button variant='primary' onClick={handleClose}>
            Save Changes
      <Button variant='primary' onClick={(e) => handleShow(e, list)}>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *