TanyaNfyz
TanyaNfyz

Reputation: 21

React - FETCH method doesn't read my .json file

I have an issue to fetch my data. The code below is not working. It's returning null however there's some data in that JSON file. If I enter a HTTP link with some JSON data it works but can't read a local file.

import React, { useState, useEffect} from "react";

export default function DataComponent() {
    const [data, setData] = useState(null);

    async function fetchData() {
        const response = await fetch("./data");
        setData(await response.json());
    }

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <div>{JSON.stringify(data)}</div>
    );
}

Tried to move it to different folders or change a path, nothing have worked yet.

Upvotes: 2

Views: 1498

Answers (1)

MarioG8
MarioG8

Reputation: 5921

Place your json file in public folder and Try to use fetch again.

enter image description here

examples

fetch('./example.json')

fetch('example.json')

import { useEffect, useState } from "react";

export default function DataComponent() {
  const [data, setData] = useState(null);

  async function fetchData() {
    // const response = await fetch("./example.json");
    const response = await fetch("example.json");
    setData(await response.json());
  }

  useEffect(() => {
    fetchData();
  }, []);

  return <div>{JSON.stringify(data)}</div>;
}

Tested win 10 react 17.0.2

Upvotes: 2

Related Questions