2

Good Day,

I'm trying to fetch data from my local JSON file located in the public folder of my react app. I know this is a frequently asked question in SO and I've already looked up topics related to my issue beforehand but this below is the nearest one.

Fetch local JSON file from public folder ReactJS

I'm using the code below to fetch my json file:

  const getResponse = () => {
    fetch('responseScript.json')
      .then(response => { response.json() })
      .then(data => { console.log(data) })

  }

  useEffect(() => {
    getResponse();
  })

The main issue is whenever I fetch data from my json file, I get undefined and an error: enter image description here

responseScript is in the public folder. I've also checked devtools and in the network tab, I can see that the request status code is 200 OK.

I'm not sure if it adds to the issue, but I'm using typescript. I've also looked into using FileStructure and that doesn't seem to work for me also.

EDIT

My JSON structure looks like this:

[
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    },
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    },
    {
     "Category":"Some text here",
     "Issue":"Some text here",
     "Answer":"Some text here",
     "Response":"Some text here"
    }

]

The folder structure is

enter image description here

Any help is appreciated. Thanks!

13
  • seems like error pointing to bad json, examine what it actually returns Commented Oct 14, 2021 at 16:37
  • What does your directory structure look like in regard to the location of the json file? Commented Oct 14, 2021 at 16:38
  • That suggests that your "JSON" is actually HTML. Commented Oct 14, 2021 at 16:39
  • it should be fetch(myRequest).then(response => response.json()) you are not returning response.json Commented Oct 14, 2021 at 16:39
  • attach the folder structure image of the project. Commented Oct 14, 2021 at 16:48

1 Answer 1

0

use this:

  const getResponse = () => {
    fetch("./public/responseScript.json")
      .then(response => { response.json() })
      .then(data => { console.log(data) })

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

2 Comments

I'm seeing the same error
show us full folder structutre uncollapsed..

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.