Vololodymyr
Vololodymyr

Reputation: 2288

Correct way to load config into Redux application

I need to read config.json file before my application will start. This config contains urls to my back-end services. Which will be used into redux action-creators.

I have 2 approaches:

  1. fetch json and save data into state. And than get urls from state into action creators which is anti-pattern
  2. fetch json and define data as global variable. Than i can access global variables from my action-creator.

What should i do ?

Upvotes: 3

Views: 2569

Answers (3)

GibboK
GibboK

Reputation: 73938

You could consider the following solution:

  • Fetch the data from your configuration file and save its result at runtime in a module (singletone) called config.js
  • Import config.js in your application (most probably in your api module where you delegate fetch operations with the server).

IMO the main advantage of this approach is that you do not pollute the the global namespace and you keep things clean using a separate module. This approach could work best for static or dynamic configurations.

To be honest do not sure if your store is the right place to keep configuration as AFAIK it was designed for maintaining the state tree of your application so could be considered the right place in case your configurations are in some how dynamic.

Upvotes: 3

Pei Han
Pei Han

Reputation: 156

  1. i will fetch json file and define it as global variable

    fetch('config.json').then(data => window.CONFIG = data)

  2. if config file contains some data which is relative to UI, you can set it to intialState in store

    const initalState = { config: window.CONFIG }

Upvotes: 1

CodinCat
CodinCat

Reputation: 15914

I will choose approach 2 because it's config not state of your app. It won't change during runtime.

But I'm not sure what your app looks like, if your config does change dynamically then putting it in the redux store makes sense to me.

Upvotes: 2

Related Questions