Using async method to load a local JSON file in React JS

Viewed 1290

Here, I am trying to load a local JSON file using the async function. I am trying to log the data in the console, any solutions?

import { useEffect } from "react";
import "./styles.css";

export default function App() {
  useEffect(() => {
   fetchItems();
});
const fetchItems = async () => {
  const res = await fetch("./users.json");
  const data = await res.json();
  console.log(data);
};

return (
  <div className="App">
    <h1>Hello CodeSandbox</h1>
  </div>
);
}

Here is my JSON file named users.json.

[
    {
        "id": 1,
        "first_name": "random",
        "last_name": "random"
    }, {
        "id": 2,
        "first_name": "random",
        "last_name": "random"
    }
]
1 Answers

You can directly import with import data from "./users.json".

Or you can use await fetch("http://localhost:3000/users.json");. For this you should keep your json in public folder.

Related