Search code examples
reactjsreact-hooksfetchuse-effect

How to fetch json data without bugs?


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


Solution

  • 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"