Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i load a JSON configuration in runtime in a React app?

I have a React app (with static content, not using Node.js) and i need to load a configuration file (JSON).

The file loading needs to be in runtime, because the configuration needs to have different data, related with the server where the application is hosted.

Due this last requirement, i can't load the file using, for instance, webpack externals, because the application doesn't update the configurations when the the JSON file is updated.

What is the best way to do that?

I've done that using the Fetch API (http request to load the file), but maybe there's a better way to do that.

like image 342
nuno.filipesf Avatar asked Sep 12 '17 10:09

nuno.filipesf


1 Answers

You have at least 2 options here depending on your use case:

  1. Fetch the config like you mentioned. What I usually do in these scenarios is put a data-attribute on my root with the server url that will hold my config data (as in my case I don't know the domain of the server at compile time).

i.e: <div id="root" data-url="yourDomain.com/app"></div>.

Grab this value and pass it as prop in to the App. index.js for example:

    const root = document.getElementById('root');
    const url = root.getAttribute('data-url');
    const configPromise = fetch(url);
    configPromise.then((res) => res.json())
      .then(config => render(<App config={config} />, root) );
  1. Store the config data to a global object variable and use it inside your app.

I like the first option more even though it forces you to do an ajax request.

like image 183
Sagiv b.g Avatar answered Sep 28 '22 01:09

Sagiv b.g