1

I have a collection of URL's, that I want to use as a constant file in my React-Native app.

export default {
  HTTP_HOST: 'http://192.168.1.5',
  SIGNUP_API: this.HTTP_HOST+'/services/registerMobileNumber.php',
};

When I import constant.js like below

import GLOBAL from '../../constant.js';

GLOBAL.HTTP_HOST works fine, but GLOBAL.SIGNUP_API gives undefined/services/registerMobileNumber.php

How can I refer the key HTTP_HOST in the same object?

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87

3 Answers3

1

JavaScript (JSON) does not allow you to do this. However, you do have quite a few options of other ways to accomplish the desired behavior:

How can a Javascript object refer to values in itself?

Galupuf
  • 2,827
  • 1
  • 12
  • 29
1

You can do this by two method 1. Don't reference it by this use the OUTER Variable Name like:

const SERVICES = {
             HTTP_HOST:'http://192.168.1.5',
             SIGNUP_API: SERVICES.HTTP_HOST+'/monopoly/services/registerMobileNumber.php'
        };
export default SERVICES;
  1. You can use custom getter and setter for key SIGNUP_API.

    const SERVICES = {
      HTTP_HOST:'http://192.168.1.5',
      get SIGNUP_API() {
        return this.HTTP_HOST+'/monopoly/services/registerMobileNumber.php'
      }
    }
    export default SERVICES;
    

Now both of the method will give you same output. For Example -

import GLOBAL from '../../constant.js';
console.log(GLOBAL.SIGNUP_API) 

gives the output,
http://192.168.1.5/monopoly/services/registerMobileNumber.php

Supermacy
  • 1,429
  • 15
  • 24
0

Apparently there was no solution to this..

So I tried this and it worked.

const HTTP_HOST = 'http://192.168.1.5';

const SERVICES = {
    SIGNUP_API: HTTP_HOST+'/monopoly/services/registerMobileNumber.php'
}

export default SERVICES;
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87