0

I am having some trouble with my local json file not being recognized in React with fetch()

Code below:

import React, { useState, useEffect } from 'react';
import Datatable from "./datatable";
import Data from './data/data.json';
import './App.css';

require("es6-promise").polyfill();
require("isomorphic-fetch");

export default function App() {
  const [data, setData] = useState([])
  const [q, setQ] = useState("");
  const [searchColumns, setSearchColumns] = useState(["first_name", "last_name"]);

  useEffect(() => {
    fetch(Data)
    .then(response => response.json())
    .then(json => setData(json));
  }, []);

... some add'l code continues which I can add if helpful.

File map if helpful

I'm literally just getting a blank page. I also tried fetching the actual path to the json file out of curiosity, but I received a webpack loader error.

Any insights would be helpful.

Harry J
  • 1,571
  • 3
  • 10
  • 23
  • It depends on what you are trying to do, but you may not need fetch at all (fetch is for getting files from a web server, not local files). See: https://stackoverflow.com/questions/50007055/fetch-request-to-local-file-not-working – mahi-man Aug 16 '20 at 23:35

1 Answers1

0

If you already have your data locally, you don't need to fetch it on remote server. Try is instead :

export default function App() {
  const [data, setData] = useState([])
  const [q, setQ] = useState("");
  const [searchColumns, setSearchColumns] = useState(["first_name", "last_name"]);

  useEffect(() => {
    // use your data here
    setData(Data);
    console.log('data', Data);
  });

  return(
    <div>yeah it works !</div>
  )
}

Here is an working example : https://stackblitz.com/edit/react-can3gq?file=data.json

mickdev
  • 2,485
  • 9
  • 15