Search code examples
jsonreactjsfileexternalcreate-react-app

Proper way to include lists and other external data inside a TypeScript React App


I created a React App using the create-react-app npm package. Everything works fine, however I'm not sure how to handle external files.

I created a POC that holds a json object of the entries for a select field. I can import the object and it works properly. However, I'm used to having files like this available on the server so that they can be edited without having to re-build the program.

I converted the file to a .json and I'm able to import it without a problem. However, if I try to move it to the "public" folder, I'm no longer able to import it. If it remains within the src folder it gets included within the bundle and I'm not able to edit it directly.

Is including the file within the bundle the standard way of handling data that can change (whether by requiring update or i18n)??? If not, how do I go about configuring the app to allow me to import it from the public folder once it's deployed?


Solution

  • This should work:

    Add data.json to public directory and use fetch in componentDidMount

    componentDidMount() {
      fetch('data.json').then(data => {
        data.json().then(response => {
          console.log(response)
          this.setState({ data }); // you can set data to state
         });
      })
    }
    

    content of data.json

    {
      "data": "some data"
    }
    

    If you are trying to use some external data e.g. from server, you should not import it like any other files (i.e. import a.js from './a') you should make HTTP request in order to retrieve these data