How do you handle relative filepath fetch requests in Create React App?

Viewed 13

I have a bunch of unchanging data I'd like to retrieve based on user input. Loading all of them at once would be too much to handle, and since the data never changes, I have a simple lookup system in place. I have a folder called data which stores all necessary JSONs, saved as an id. I planned to create the relative file path to that ID based on the user input. However, it seems like relative file paths work very differently in the development environment (npm start) compared to the final build (npm run build).

Consider this example:

App.js

import "./App.css";
import React, { useEffect } from "react";

function getJSON() {
  fetch("data.json", { //relative file path goes here
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  })
    .then((response) => {
      console.log(response);
      return response.json();
    })
    .then((responseJson) => {
      console.log(responseJson);
    })
    .catch((error) => {
      console.log(error);
    });
}

function App() {
  useEffect(() => {
    getJSON();
  }, []);
  return <div className="App"></div>;
}

export default App;

Currently, data.json is one file in the src folder. No matter what I changed the file path to or where I placed the JSON file, it always returned a 404 error.

Is this a byproduct of how Create React App works? Is the starting point of the relative path wrong? On another note, if this is bad practice for hard-coded values, please let me know.

0 Answers
Related