3

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
  • Browser cannot access local file,import it directly or export json online Commented Aug 17, 2021 at 9:57

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

just bumped into the same problem, and this answer helped! Especially second method with fetch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.