0

So i want to fetch from my local data.js file. It looks like this:

{
  product_name: [
  {'name': 'hello',
   'lastName': 'hello'
   }, {'name': 'hi',
   'lastName': 'hi'}
]
}

Is this valid JSON? My code that I'm fetching it with looks like this :

fetch('./data.json')
        .then(res=> res.json())
        .then(text=> console.log(text))
 

After this, I get an error in my console.log. Also when I go to the network tab and click on data.json It tells me that javascript needs to be enabled, what does that mean? Thank you guys

1 Answers1

0

I might be able to solve your answer.

First things

You must remember to format the JSON so that it is readable by a user, if you are currently developing your program. In production mode, you can skip this step, but it is a good practice.

Next, The JSON you have does not seem to use quotes for keys. This is a must for JSON. If you don't like the quotes, use json5, JSON's friendlier brother.

Next,

This explains about JSON with fetch.

The Fetch API returns a response stream in the promise. The response stream is not JSON, so trying to call JSON.parse on it will fail. To correctly parse a JSON response, you'll need to use the response.json function. This returns a promise so you can continue the chain.

I see that you have done it, but are forgetting the GET method mentioned in the above post. And, use return keyword to pass the JSON to the next promise. So, your corrected JS code will be:

fetch('./data.json', { method: "GET" })
        .then(res => return res.json())
        .then(text => console.log(text))

I am not an expert in React, but these are some common things I can correct.

2nd Part of Question

I do not really know why it says JavaScript needs to be enabled. Maybe go to your settings and enable JavaScript? Or, if you use an ad-blocker, try disabling it once and see.

Final Words

I think I have solved a part of your question.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
RealZombs
  • 135
  • 1
  • 12