Question: How to pass application settings to store


How to pass application settings to store

Answers 1
Added at 2016-04-15 12:04

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:

  • Passing the setting from the component to the action, to that I receive it on every store listener.
  • Use some DI container which is initialized in my index.js and can be used in my store

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

Answers to

How to pass application settings to store

nr: #1 dodano: 2016-04-15 13:04

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).

Source Show
◀ Wstecz