0

I'm using react and working on getting json files in the component.

I want to get the input.json file using fetch, but it's not data in the console. Why is this and how do I get the data?

input.json

{
    "formId": 1,
    "title": "from",
    "items": [{
      "itemId": 1,
      "title": "style",
      "formType": 1,
      "options": [{
        "id": 1,
        "text": "one"
      }, {
        "id": 2,
        "text": "two"
      }, {
        "id": 3,
        "text": "three"
      }]
    }

App.js

import React from 'react';
import './App.css';
import inputData from './assets/input.json';

function App() {

  const getData = () => {
    fetch(inputData).then(response => {
               return response;
             }).then(data => {
               console.log(data);
             }).catch(err => {
               console.log(err)
             });
  }

  getData();

  return (
    <div className="App">
      <h2>Fetch</h2>
    </div>
  );
}

export default App;

console.logenter image description here

smooth97
  • 73
  • 2
  • 9

3 Answers3

0

you are missing something in your result fetching, it should be

 fetch(inputData).then(response => {
            response.json().then(data => {
            console.log(data);
          }).catch(err => {
            console.log(err)
          });


Ariel Batista
  • 144
  • 1
  • 5
0

Did you try with parsing response to json format?

something like this:


import inputData from '../assets/input';

const getData = () => {
 fetch(inputData).then(response => {
const result = response.json()
            return result;
          }).then(data => {
            console.log(data);
          }).catch(err => {
            console.log(err)
          });
}
  • An error occurs when you perform response.json() because it is already a json file. Thank you for your answer! – smooth97 Sep 23 '19 at 13:36
0

Try this,

import React from 'react';
import './App.css';
import inputData from './assets/input.json';

function App() {

  const getData = () => {
    fetch(inputData).then(response => {
                console.log(response);
                console.log(response.data);
              }) catch (err => console.log("err",err))
  }

  getData();

  return (
    <div className="App">
      <h2>Fetch</h2>
    </div>
  );
}

export default App;
Dixit Savaliya
  • 413
  • 3
  • 7