-1

I want to fetch in react using useEffect hook but there is an issue
this is my code from a landing-page.jsx file :

import "./landing-page.css";
import { useState, useEffect } from "react";

export default function Landing_page() {
const [data, set_data] = useState(null);
useEffect(() => {
    fetch("./db.json")
        .then((res) => res.json())
        .then((d) => console.log(d));
}, []);

and this is my db.json file :

{
"projects": [
    {
        "id": 1,
        "name": "Lorem ipsum dolor sit",
        "level_name": "newbie",
        "level_number": "1",
        "description": "Fugiat quibusdam tempore explicabo earum perferendis, pariatur dolores. Vitae perspiciatis officia nobis?",
        "preview_link": "https://google.com",
        "github_link": "https://google.com"
    }
]

} I want to get this JSON file inside landing-page.json file with useEffect and fetch but it doesn't work and shows this error in the console:
enter image description here

** and remind you both these files are in the same folder

skyboyer
  • 22,209
  • 7
  • 57
  • 64

3 Answers3

1

Try this :

useEffect(() => {
  const getProjects =async ()=>{
  const res = await axios.get("./db.json");
  set_data(res.projects)
  getProjects()
}
   
}, []);
Yassin Mo
  • 347
  • 2
  • 9
1

by using JSON-server then you will need to specify the full URL from your localhost. not the path to the file. the key of your JSON which is projects is your API that you're going to call. http://localhost:3000 is your localhost that is needed to make your request.

useEffect(() => {
    fetch("http://localhost:3000/projects")
        .then((res) => res.json())
        .then((d) => console.log(d));
}, []);
Amr yasser
  • 408
  • 5
  • 10
1

You should place the db.json file inside the public folder because during runtime the "/" path is going to be the public folder and not the src folder. Alternatively you can import the db.json file if it's in your src folder. import db from './db.json'.

As others have stated. In a real DB fetch situation, you're going to specify the full path to the resource such as "URL:PORT/endPointName"

Ryan Zeelie
  • 1,320
  • 5
  • 12