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?

3
  • 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. Commented Sep 28, 2020 at 13:17
  • Does this answer your question? Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Commented Sep 28, 2020 at 13:17
  • try console.logging outside useEffect Commented Sep 28, 2020 at 13:18

2 Answers 2

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).

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

3 Comments

using this for some reason gives me [object object]
What do you mean by "gives me"? Is this the output of console.log()?
That's maybe fine depending on how smart your browser is. You can do console.log('data', JSON.stringify(data)) in case your browser isn't very smart.
0

simply

fetch(url)
  .then(res => res.json())
  .then(data => setData(data))

Comments

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.