mercredi 21 février 2018

Is there anything wrong with using an imported config object in javascript/react

I have these settings passed to my component and they are used in various places around the app. Instead of carrying them with me all over the place I initialise a config object with them and then just import it when I need it.

Is there anything wrong with it?

Isn't this how dependency injection works?

Javascript resolves to the same object if the import is in the same place, right?

Example

// ./cmsSettings.js
const cmsSettings = {};
cmsSettings.initialise = (props) => {
  cmsSettings.settings = { ...props };
};

export default cmsSettings;

// ./App.jsx
import cmsSettings from './cmsSettings';
...

class App extends Component {
  constructor(props) {
    super(props);
    cmsSettings.initialise(props);
  }

  render() {
    return (
      <MyComponent />
    );
  }
}

export default App;

The props contain the object with the properties passed by the site (locales, languages, some ids, etc). I need them in various places for when I am getting language translations, making requests to APIs using specific ids and such.

So I have a config file that I initialise when the component is loaded and then import in a file that I need it. It will return the same object because javascript.

i.e.

// ./apiService
import cmsSettings from '../cmsSettings';
...

const get = () => {
  const url = `${BaseUrl}?id=${cmsSettings.settings.context.ee}&lang=${cmsSettings.settings.context.locale}`;

  return Request.get(url).then(response => response.body.data);
};

export default {
  get,
};

My other concern is that I have this initialise function which also has the benefit that allows me to "mock" the object in my unit tests.

Any opinions, advice, for, against?

Aucun commentaire:

Enregistrer un commentaire