ReactJS - get json object data from an URL

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.


Edit: Use fetch for making API calls.

fetch(http://www.example.com/api/json/x/a/search.php?s=category)
  .then(response => response.json())
  .then((jsonData) => {
    // jsonData is parsed json object received from url
    console.log(jsonData)
  })
  .catch((error) => {
    // handle your errors here
    console.error(error)
  })

Fetch is available in all modern browsers.

Tags:

Json

Reactjs