-2

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.

stacktrace2234
  • 1,172
  • 1
  • 12
  • 22
  • and [Can a JavaScript object property refer to another property of the same object?](https://stackoverflow.com/questions/3173610/can-a-javascript-object-property-refer-to-another-property-of-the-same-object), [Can I reference other properties during object declaration in JavaScript](https://stackoverflow.com/questions/4618541/can-i-reference-other-properties-during-object-declaration-in-javascript) – pilchard Mar 21 '23 at 10:40
  • What this `backendUrls` is? Is it the part of data or a simple JS object? – Neha Soni Mar 21 '23 at 10:45

1 Answers1

-1

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

        }

    }
}
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26