javascript - How can i load a JSON configuration in runtime in a React app? -
i have react app (with static content, not using node.js) , need load configuration file (json).
the file loading needs in runtime, because configuration needs have different data, related server application hosted.
due last requirement, can't load file using, instance, webpack externals, because application doesn't update configurations when the json file updated.
what best way that?
i've done using fetch api (http request load file), maybe there's better way that.
you have @ least 2 options here depending on use case:
fetch config mentioned, in these scenarios put
data-attribute
on root server url hold config data (as in case don't know domain of server in compile time).
i.e:<div id="root" data-url="yourdomain.com/app"></div>
.
grab value , pass prop in app.index.js
example:const root = document.getelementbyid('root'); const url = root.getattribute('data-url'); const configpromise = fetch(url); configpromise.then((res) => { res.json().then((json) => { const config = json.parse(json); render(<app config={config} />, root ); }); });
- store config data global object variable , use inside app.
i first option more though forces ajax request.
Comments
Post a Comment