schneck
schneck

Reputation: 10847

How to pass application settings to store

In terms of clean react application design, I'm sure sure how to pass around application settings to modules which are not part of the component tree.

E.g. I connect to a REST API and therefore need to propagate the hostname to the components, but also to the store - I'm using Reflux.

Passing the setting down to components can be easily achieved via contexts, but since the store is not part of it, what's the cleanest way?

So far, I consider these approaches:

Both don't seem to be ideal for me. Any hints appreciated!

Upvotes: 0

Views: 940

Answers (1)

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13174

In most cases you should not keep application settings in store.

You should think about your application like some kind of function that receives state as parameter and returns view. Changes in application state (usually) lead to changes in resulting view. Flux stores are the way you're keeping this state. API hostname is not that stuff which you expect to affect your application. It is just an information payload that your app need to know to work correctly (say configuration, not the settings). So, you should keep it as information payload. Module, class, global variable, some kind of DI, you can consider anything that you find useful to work with.

I usually create separate module exporting object with all configuration. Something like:

const config = {
  api: {
    hostname: 'localhost',
    port: 3000
  }
  // ...
};

export default config;

And then just importing it. Something like:

import config from "../config";

const api = new API(config.api); // just for example

But if you really need to work with some kind of settings that can affect UI (an example is delay to show popup; it example can be even better if we consider changing this delay depends on user's actions) you should create Settings store and work with it like with a regular flux store (subscribing to change, changing with actions so on).

Upvotes: 1

Related Questions