skip to Main Content

Basically I want to create an object that holds all the backend api urls.

backendUrls: {
  pathParts: {
    house: '/house',
    office: '/office'
  },
  baseUrl: 'http://localhost:8080',
  houseUrl: this.baseUrl + this.pathParts.house
}

But when I start the project (it is VueJS if its important) and I want to open the page the console says: TypeError: Cannot read properties of undefined (reading 'house').

Thanks in advance.

2

Answers


  1. You can reference other properties of the same object when defining a new property if you make it a method. Here’s an example:

    const backendUrls = {
      pathParts: {
        house: '/house',
        office: '/office'
      },
      baseUrl: 'http://localhost:8080',
      houseUrl: function() {
        return this.baseUrl + this.pathParts.house;
      },
      officeUrl: function() {
        return this.baseUrl + this.pathParts.office;
      }
    };
    
    console.log(backendUrls.houseUrl());

    If we make the houseUrl property a getter method, it can be accessed like a regular property without the need to call it as a function.

    Here’s an updated version of the backendUrls object with houseUrl as a getter method:

    const backendUrls = {
      pathParts: { house: '/house', office: '/office' },
      baseUrl: 'localhost:8080',
      get houseUrl() {
        return this.baseUrl + this.pathParts.house;
      },
      get officeUrl() {
        return this.baseUrl + this.pathParts.office;
      },
    };
    
    console.log(backendUrls.houseUrl);

    Now we can access the houseUrl and officeUrl properties as follows:

    console.log(backendUrls.houseUrl); // localhost:8080/house
    console.log(backendUrls.officeUrl); // localhost:8080/office 
    

    Note that we call houseUrl and officeUrl as if they were regular properties, without using parentheses to indicate a function call. This is because they are now defined as getter methods.

    Login or Signup to reply.
  2. The baseUrl and pathParts do not exist at the instant that you are creating houseUrl.

    They all start existing at effectively the same time, so they can’t reference each other.

    If you want one variable to depend on another, you need it to be created later. Try creating houseUrl in a computed property. Inside a computed property you are free to access items initialised in data().

    
    data(){
        return {
            pathParts: {
                house: '/house',
                office: '/office'
            }
            baseUrl: 'http://localhost:8080',
        }
    }
    
    computed:{
        
        backendUrls() {
           return   { 
                houseUrl: this.baseUrl + this.pathParts.house
    
            }
    
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search