The error message "TypeError: Trying to access property 'first_name' of an undefined variable on an ES6 model" is causing

I encountered an issue while trying to implement a JSON API in an ES6 model. The error message I received was: TypeError: Cannot read property 'first_name' of undefined.

Here is the JSON API:

class UserModel {
    constructor(data) {
        this.id = data.id;
        this.first_name = data.attributes.first_name;
        this.last_name = data.attributes.last_name;
        this.username = data.attributes.username;
        this.email = data.attributes.email;
        this.created_at = data.attributes.created_at;
        this.link = data.links.self;
    }

    get getId() {
        return this.id;
    }

    set setId(value) {
        this.id = value;
    }

    get getFirstName() {
        return this.first_name;
    }

    set setFirstName(value) {
        this.first_name = value;
    }

    get getLastName() {
        return this.last_name;
    }

    set setLastName(value) {
        this.last_name = value;
    }

    get getUsername() {
        return this.username;
    }

    set setUsername(value) {
        this.username = value;
    }

    get getEmail() {
        return this.email;
    }

    set setEmail(value) {
        this.email = value;
    }

    get getCreatedAt() {
        return this.created_at;
    }

    set setCreatedAt(value) {
        this.created_at = value;
    }

    get getLink() {
        return this.link
    }

    set setLink(value) {
        this.link = value
    }
}

Can anyone provide assistance on how to resolve this issue?

Answer №1

It seems like there might be confusion in how you're utilizing the getter method to retrieve the value. A key guideline to follow is to ensure that your set/get pairs are consistently named with the property name. These should differ from the property that holds the actual value. For instance, you could use _id for the value property name and id for the relevant get/set name.

class PersonModel {

  constructor(data) {
    this._id = data.id;
    this._firstName = data.attributes.first_name;
  }

  get id() {
    return this.id;
  }

  set id(value) {
    this._id = value;
  }

  get firstName() {
    return this._firstName;
  }

  set firstName(value) {
    this._firstName = value;
  }

}
const data = {
  "type": "user",
  "id": 2,
  "attributes": {
    "username": "madelynn81",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdbced6c3c0dd999cefc2c6c3c3dc81cdc6d5">[email protected]</a>",
    "first_name": "Emile",
    "last_name": "Veum",
    "created_at": "2018-11-17 11:48:13"
  },
  "links": {
    "self": "http://test.test/api/v1/user/2"
  }
}

const person = new PersonModel(data);
console.log(person.firstName)

Answer №2

It may vary depending on your objectives, but typically in javascript, a more straightforward syntax is utilized, and objects closely resemble arrays.

Let me provide a brief illustration:

    const information = {
      "type": "customer",
      "id": 5,
      "attributes": {
        "username": "alex123",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84f5fef1f0fff290e1f6f1f3f5eaf7f5f4ff32fef5e6">[email protected]</a>",
        "first_name": "Alex",
        "last_name": "Johnson",
        "created_at": "2019-05-25 09:24:33"
      },
      "links": {
        "self": "http://sample.sample/api/v1/customer/5"
      }
    }

    const customer = { 
      id: information.id,
      firstName: information.attributes.first_name,
      // other properties,
    };

    console.log(customer.firstName);

As a matter of fact, if you observe closely, your data itself already functions as an object.

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

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

Leverage PHP variables within AJAX requests

I am currently working on implementing a specific functionality on the page "videos.php" (please note that this is all contained within a PHP echo statement): First, when a user clicks .star_' . $pvid_ID . ', it triggers the submission of a vid ...

Strategies for making a child div fade out when the parent div is hovered over

I have a div with the class name ordershape and inside it, there is another div called fad-res. My goal is to display the corresponding fad-res when I hover over a specific ordershape, while hiding the other divs. <div class="ordershape"> & ...

Is there a way to inject C++ text into an input field on a webpage using QWebEngine?

I want to integrate a website with QWebEngine to manipulate input commands using Qt's event filters and more. The specific website I am working with requires a username/email and password, and I aim to manage the input of this text on my end. This inv ...

Using Node to parse XLSX files and generate JSON data

Hello, I am currently utilizing the js-xlsx package which can be found at this link. My inquiry is how to successfully parse an xlsx file with merges and convert it into JSON format. You can view what the excel sheet looks like here. Ultimately, the JSON o ...

Is there a JavaScript function available that can enable the placeholder attribute to function properly in Internet Explorer?

I currently have numerous input tags in my project that utilize a placeholder attribute, such as the following: <input id="Name" name="Name" placeholder="Name Goes Here" type="text" value=""> Is there a JavaScript function that I can include in my ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

JavaScript and AJAX: Dynamically Create URLs

I don't have any experience with web development, so could you please explain in detail? If my questions are unclear, feel free to ask for more information. Imagine I have a webpage with the following URL: www.mycompany.com/category1 This page has ...

When the page is loaded, ensure a condition is met before displaying a modal pop-up using AngularJS

Just starting out with AngularJS and looking to implement a modal pop up? I've tried using the modal on button click from the Angular dialog demo tutorial. Now, I want to show the pop up based on a condition when the page loads. The idea of automatic ...

converting time stamps to written text

Is there a JavaScript library available that can convert a timestamp (Date Java class value) to text? For example: Just two minutes ago 4 hours back 23 August 2009 Does such a library exist? If not, I'll take on the challenge of implementing it ...

A guide on retrieving information from a JSON file in Vite with ReactJS

Note vitejs build tool is utilized for creating a reactjs-app. Question During development, I can successfully access data.json on the server. However, when it comes to production, I encounter an issue where data.json cannot be retrieved. How can this be ...

Implement necessary validation for the country code selection on the dropdown menu using the intl-tel-input jQuery plugin

Check out the intl-tel-input plugin here Currently, I am utilizing this plugin and attempting to implement required validation on the country code drop-down. However, the plugin seems to be restricting me from achieving this. I have made several attempts ...

What are the steps to apply an AngularJS filter for formatting values within an array?

While I have experience using angular filters for formatting primitive values like numbers into currency formats, I am now faced with the challenge of applying the same filtering to an array of values. For example: price = 1 prices = [1,2,3] If I were to ...

Instructions on obtaining a distinct daily array from the weather API array that provides a detailed 5-day weather report every 3 hours

Seeking assistance with my weather app development on React using axios with the openweathermap.org API. Currently stuck on getting data formatted in a specific way from the 5-day forecast it provides, totaling 40 reports over the 5 days. The API response ...

Arrangement of pipe operators in RXJS Angular 5

Do you think my operators are in the correct order? The code snippet below shows that the console logs from the two taps display the same values. Something seems off, right? return this.pcs.getAvailableMaterials(currentProduct.id).pipe( map( ...

The method of utilizing React with Redux to display component properties

I am currently trying to include my common component in my main.js file Successfully implemented this However, when attempting to print my Redux data values in the common component, I created a method called handleClickForRedux to handle this task. Even af ...

What is the best way to convert template interpolation using different words into a correct expression syntax in JavaScript regex?

I have a string that contains template interpolation along with words that are not inside the interpolation. The string can be in one of these various forms: foo{{bar}} {{foo}}bar foo{{bar}}baz {{foo}}{{bar}} foo {{foo}} {{foo}}bar{{baz}} The text interpo ...

How can selenium be best utilized in a production environment?

After creating tests for my website using selenium and javascript, I am now looking to implement them in a production environment. Currently, I have been running these tests locally with the Chrome driver. In the start section of my package.json, I execu ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...