Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - get json object data from an URL

Tags:

json

reactjs

How do I get data from an URL into ReactJS.

The url is of the following type: http://www.domain.com/api/json/x/a/search.php?s=category

which, if typed in a browser, will display a json object.

How do I load it to ReactJS.

To start with, I started by:

const dUrl = "http://www.the....";

console.log(dUrl);

but obviously it displays the url not the content (which, I will be able to filter - it's just this initial step of loading it into an object that I don't know)

Edit: I'd rather not use jQuery.

like image 348
Wasteland Avatar asked Aug 18 '16 13:08

Wasteland


People also ask

How do I extract a JSON file from a website?

The first step in this process is to choose a web scraper for your project. We obviously recommend ParseHub. Not only is it free to use, but it also works with all kinds of websites. With ParseHub, web scraping is as simple as clicking on the data you want and downloading it as an excel sheet or JSON file.


1 Answers

Try using Fetch API, it's recommended by Facebook. You should avoid mixing in jQuery with ReactJS and stick to the ReactJS way of manipulating the DOM.

function getMoviesFromApiAsync() {
   return fetch('https://facebook.github.io/react-native/movies.json')
   .then((response) => response.json())
   .then((responseJson) => {
     return responseJson.movies;
   })
   .catch((error) => {
     console.error(error);
   });
}

Or using async/await

async function getMoviesFromApi() {
  try {
    let response = await fetch('https://facebook.github.io/react-native/movies.json');
    let responseJson = await response.json();
    return responseJson.movies;
   } catch(error) {
    console.error(error);
  }
}

https://facebook.github.io/react-native/docs/network.html

I'm aware the URL is for React Native's documentation, but this apply for ReactJS as well.

like image 158
Hylle Avatar answered Sep 28 '22 00:09

Hylle