0
votes

I’m working on a React project built with create-react-app and am confused about how to reference a local JSON file wth useEffect().

My directory structure looks like:

public
src
    components
    data
        test.json
    App.js

In App.js, I use useEffect() with fetch() to grab the JSON file.

useEffect(() => {
        const getData = () => {
            fetch('./data/test.json'
            , {
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            }
            ).then(function(response) {
                return response.json();
            }
            ).then(function(myJson) {
                // lots of processing happens
            });
        };
        getData();
        setTheContent(toUse);
    },[slug]);

But I get a 404 in the console for http://localhost:3000/data/test.json.

If I put my data folder in the public directory (and leave the fetch path as is), it works fine, but my understanding is that I shouldn’t use the public directory for that.

One other bit of info: I’m using useEffect() rather than just importing the JSON file because I eventually need to import different data files based on a URL parameter.

2
you can import the file into your app.js like so: import data from './data/test/json' and then in your fetch you can just reference the data import - Robert Terrell

2 Answers

2
votes

Since CRA uses webpack, URLs within the src folder are converted ("optimized" by webpack).

Therefore, your only options are to use require or import on the file's URL, or to move the file to public folder (which then will not be processed by webpack).

Either way, you should refactor it when you will fetch it from a valid URL.

// Use require
const data = require("./data/data.json");

// Or import it beforehand
import data from "./data/data.json"

setData(data);
1
votes

You can place files in public folder, which doesn't contain any sensitive data and which are files help you to render content. While serving the content to url files under public folder only taken into consideration, files outside the public folder are not considered (other files are only for development purpose). While building a project the files in src folder are convert into chunk of js files and return a directory which contains files from public folder and files which are builded from the src folder.