1

I want to load a JSON settings file dynamically in my react application.

I'm using webpack and when I import the file like:

import appSettings from './appSettings.json';

Or require it:

const appSettings = require('./appSettings.json');

It compiles the json and not load it dynamically (e.g. not changeable during runtime).

Can someone assist ?

4
  • Is your file path correct? Commented Mar 16, 2021 at 9:01
  • It is. if not - I wouldn't get data Commented Mar 16, 2021 at 9:12
  • Check our @Nkubito Pacis' answer. Does it help? Commented Mar 16, 2021 at 9:25
  • I'm not sure if React is really designed to handle this. Why are you writing changes to a JSON text file rather than making changes in a settings state? It would make more sense to use the state as your single source of truth and push changes to file based on the state rather than the other way around. Commented Mar 16, 2021 at 10:04

2 Answers 2

1

You should consider adding useEffect hook so that it re-renders your page when there is a change in the json

    import appSettings from './appSettings.json';
    import {useEffect} from 'react';
    useEffect(()=>{
       //code to run whe the json has loaded   
},[appSettings])
Sign up to request clarification or add additional context in comments.

1 Comment

Will that work? I think the imports are only loaded once when the file is first run.
1

At last, what I did is loading the file with axios in the root of my app.

  const [appSettings, setAppSettings] = React.useState<any>(null);
  React.useEffect(() => {
    axios.get('./appSettings.json').then((response: any) => {
      setAppSettings(response.data);
    });
  }, [appSettings && appSettings.data]);

  return (
    appSettings &&
    appSettings.baseUrl && (
      <Layout className={styles.root}>
        <MyApp appSettings={appSettings} />
      </Layout>
    )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.