0

I know this issue has been discussed before, but all solutions i have found are from years ago, and do not work.

What i need to do, is to load some config fields from a JSON file, sitting in the public directory of my React app. Just a static asset, outside of the build process

When i try fetching it using AJAX, i get an error on an "Unexpected token ':'". My config.json file looks simply like this:

{
    "name": "yoyo"
}

It's located in the public directory of a create-react-app program. Is there any way this can be done?

Edit: everything is working, i just had some stupid mistake

i.brod
  • 3,993
  • 11
  • 38
  • 74

2 Answers2

0

Why don’t you just import it instead of doing request? If you are doing it for any reason, have you tried something like JSON.parse?

0

I updated my question when I noticed you wanted to load a JSON file from the public directory of your project.

To do this, use fetch and load the file present from the public folder, then set it for use inside your main component (e.g.: App.js).

Here's an example using React Hooks:

import React from "react";
import "./styles.css";

export default function App() {
  const [characters, setCharacter] = React.useState(null);

  React.useEffect(() => {
    fetch("names.json")
      .then(results => results.json())
      .then(character => setCharacter(character));
  });
  return (
    <div className="App">
      <h1>Star Wars names!</h1>
      <ul>
        {characters.map(character => (
          <li key={character.name}>{character.name}</li>
        ))}
      </ul>
    </div>
  );
}

Working example using the new useEffect hook here

Working example using good old componentDidMount here

Juan Marco
  • 3,081
  • 2
  • 28
  • 32