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.