Unable to retrieve object property-Attempting to access properties of undefined object

Can you help me figure out why I am unable to access the districts property in regions object?

const regions = [ { region: "Hlavní město Praha", districts: "Benešov, Beroun, Kladno, Kolín, Kutná Hora, Mělník, Mladá Boleslav, Nymburk, Praha-východ, Praha-západ, Příbram a Rakovník", }, ];

console.log(regions.filter((r) => r.region === regionState)[0].districts)

I'm encountering an error that says

Uncaught TypeError: Cannot read properties of undefined (reading 'districts')

import React, { useState } from "react";
import { Form, Card, Button } from "react-bootstrap";
import validator from "validator";

const StepOne = ({ nextStep, handleFormData, values }) => {
  const [error, setError] = useState(false);
  const [regionState, setRegionState] = useState("");

  const regions = [
    {
      region: "Hlavní město Praha",
      districts:
        "Benešov, Beroun, Kladno, Kolín, Kutná Hora, Mělník, Mladá Boleslav, Nymburk, Praha-východ, Praha-západ, Příbram a Rakovník",
    },
  ];

  const twoCalls = (e) => {
    handleFormData("region");
    setRegionState(e.target.value);

  };
  console.log(regions.filter((r) => r.region === regionState))

  const submitFormData = (e) => {
    e.preventDefault();

    if (
      validator.isEmpty(values.propertyType) ||
      validator.isEmpty(values.region) ||
      validator.isEmpty(values.district)
    ) {
      setError(true);
    } else {
      nextStep();
    }
  };

  return (
    <div>
      <Card style={{ marginTop: 100 }}>
        <Card.Body>
          <Form onSubmit={submitFormData}>
            <Form.Group className="mb-3">
              <Form.Label>Property Type</Form.Label>
              <Form.Select
                style={{ border: error ? "2px solid red" : "" }}
                onChange={handleFormData("propertyType")}
              >
                {" "}
                <option>Select Property Type</option>
                <option value="House">House</option>
                <option value="Apartment">Apartment</option>
                <option value="Land">Land</option>
              </Form.Select>
              {error ? (
                <Form.Text style={{ color: "red" }}>
                  This field is required
                </Form.Text>
              ) : (
                ""
              )}
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>Region</Form.Label>
              <Form.Select
                style={{ border: error ? "2px solid red" : "" }}
                onChange={twoCalls}
              >
                {" "}
                <option>Select Region</option>
                {regions.map((region) => (
                  <option value={region.region}>{region.region}</option>
                ))}
              </Form.Select>
              {error ? (
                <Form.Text style={{ color: "red" }}>
                  This field is required
                </Form.Text>
              ) : (
                ""
              )}
            </Form.Group>
            <Form.Group className="mb-3">
              <Form.Label>District</Form.Label>
              <Form.Select
                style={{ border: error ? "2px solid red" : "" }}
                onChange={handleFormData("district")}
              >
                {" "}
                <option>Select District</option>
 
               
              </Form.Select>
              {error ? (
                <Form.Text style={{ color: "red" }}>
                  This field is required
                </Form.Text>
              ) : (
                ""
              )}
            </Form.Group>

            <Button variant="primary" type="submit">
              Continue
            </Button>
          </Form>
        </Card.Body>
      </Card>
    </div>
  );
};

export default StepOne;

Answer №1

If the variable "regionState" fails to match any of the regions listed in "regions," then nothing will be filtered out from the array, resulting in no "districts" attribute at index 0.

You can confirm this by displaying either the filtered array or its length:

let filteredArr = regions.filter((r) => r.region === regionState);
console.log(filteredArr.length);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for designing a movable image

I'm looking to implement a feature where the user can drag and drop an image anywhere on the page. Once the user places the image, its position will be saved so that when they revisit the page, it will be in the same location. Thank you! ...

Calculating the number of rows in a dynamic jQuery table

I have a table structured like this: <div class="row"> <input type="button" id="btnAddGatePass" value="Add Gate Pass Requester" /> <div class="table-responsive"> <table id="gatePass" class="table table-striped table-ho ...

The $.parseJSON function accurately retrieves valid items but also presents an endless stream of undefined

Currently, I am in the process of developing a Flask application that fetches teams from a football league. The teams_list method returns the result of an AJAX request. While the output is correct, it seems to trigger an infinite loop that significantly sl ...

Having trouble accessing the scrollHeight property of null when using Selenium WebDriver

I am currently working on a function in my code that is responsible for scrolling the page. This particular function was inspired by code used to scrape Google Jobs, which can be found here. However, I encountered an error that reads "javascript error: Ca ...

Guide on how to transmit an error message from PHP when handling a jQuery Ajax post request

Greetings! This is my inaugural inquiry, so please understand if I am a bit apprehensive. I am facing an issue in the following scenario... I have an Ajax request structured like this: $.ajax({ url: "test.php", method: "POST", data: { ...

Implementing Vuetify tooltips in a datatable

Attempting to incorporate tooltips into a vuetify datatable, but encountering issues. Below is the required template for using a tooltip: <template v-slot:item.state="{ item }"> <div :class="lights(item)"></div> </template> Im ...

tips for maximizing the safari browser window during automation testing

My current setup involves using Java and Selenium WebDriver for web automation. One issue I've encountered is that for Safari browser version 10.1, I need the browser to be in full screen mode before the test starts. driver.manage().window().maximize ...

What is the best way to determine and showcase the hours that have passed since the user's initial visit to the website?

Can someone provide guidance on how to finalize the hoursSinceFirstVisit() function implementation? Additionally, what content should be displayed on my HTML page? $(document).ready(function() { startTimer(); }); function startTimer() { setInte ...

What is the process for filtering records by a date greater than in the Material Table?

How can I filter the Material table by date values greater than the current value? I've been able to filter by exact date so far, but I need to filter all values that are greater than or equal to the current value in the table. <TableMaterial ...

Using React Native to iterate over a multidimensional array with the array map function

I want to iterate through a two-dimensional array like the one below: var array=[["1"],["3","8"],["4","8","3"],["4","8","3","9"],["1","8","3","9","2"],["6","8","3","9","2","1"],["4","8","3","9","2","11","2"]] Currently, this code only loops through the & ...

Searching for components in Python Selenium - a missing element

Encountered a strange issue with the "find_elements_by_css_selector" function in Selenium. Despite expecting to retrieve 10 elements, only 9 are returned consistently across various page examples. Interestingly, when testing the same selector using JavaScr ...

Transforming a circular data structure into JSON format within Firebase

https://i.sstatic.net/BhQtp.png The data returned from firebase is causing an issue when I try to stringify it: JSON.stringify(data) // where data represents the returned object This results in the error: TypeError: Converting circular structure to JSON ...

Tips for obtaining user input to place markers on a video timeline with JavaScript

I am new to Java script and I am trying to create a video player where users can click on the progress bar to place markers. Can you please review my code below and let me know if there are any errors? index.html <!doctype html> <html> <he ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...

Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below, .then((response) => { return response.json(); }) .then((jsonRespo ...

JavaScript code that loads a specific DIV element only after the entire webpage has finished loading

How can I ensure that the DIV "image" is loaded only after the entire page has finished loading? What JavaScript code should I use? <div class="row"> <div class="image"> CONTENT </div> </div> I plan to execute the functio ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...