0

I want to read data from URL using JavaScript.

below is my code,

function Parent() {
  const [data, setData] = React.useState(null);
  const url = 'someurl';
  React.useEffect(() => {
      fetch(url)
        .then(res => JSON.stringify(res))
        .then(data => setData(data);
        });
    if (data) {
      console.log('data', data);
    }

  }

logging the data state would give the result like below,

{
  "count": 2,
  "results": [{
      "title": "title1",
      "characters": [
        "character1",
      ],

    },
    {
      "title": "title2",
      "characters": [
        "character3",
      ],

    },
  ]
}

How can I read results object from URL?

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
  • Are we to assume that you're *not* getting data like that by reading data from state? If so, you have to remember that `fetch` is asynchronous, as is `setData`. You have to wait until both processes complete before you can read the data. – Heretic Monkey Sep 28 '20 at 13:17
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Sep 28 '20 at 13:17
  • try console.logging outside useEffect – Kevin.a Sep 28 '20 at 13:18

2 Answers2

1

You don't do


fetch(url)
   .then(res => JSON.stringify(res))
   //...

Instead you do


fetch(url)
   .then(res => res.json())
   //...

Reason being that res is a Response see MDN which contains more than just the data you're interested in (the response body).

Christian
  • 1,250
  • 9
  • 12
0

simply

fetch(url)
  .then(res => res.json())
  .then(data => setData(data))
bensiu
  • 24,660
  • 56
  • 77
  • 117
Ibrahim shamma
  • 399
  • 5
  • 13