19

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.

1
  • the accepted answer to this question should be changed, unless the answer is updated Commented Dec 12, 2017 at 5:53

5 Answers 5

49

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.

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

3 Comments

Having the right answer is nice. Having the right answer and a source is nicer.
upvoting because this should be the accepted answer
most of the time it will work every time. caniuse.com/#feat=fetch just IE11 is not supporting fetch.
17

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.

4 Comments

Thanks. I forgot to add - I'd rather not use jQuery. Most examples I google for gives a solution with jquery. I'd like a standard JS.
Thank you. I've tried both methods and both work. I've got one question. What's the difference in the resulting output (object). The jquery method outputs (in console log) an object that can be unfolded (into its elements) so it's nicely organised in console. The pure JS solution displays a long string of data without the ability to fold/unfold its elements. I assume the jquery method treats the data in a way that is easier to process later on. How would I do it in JS?
Actually there is no difference in both. I think the behavior in the console is just added functionality for jQuery, otherwise you'll get same data from the response. Benefit of jQuery is that it is easy to use. If you don't want to use jQuery, try fetch >> davidwalsh.name/fetch. It is just for making HTTP requests and it is lightweight too...
Downvote because adding jQuery back into a react based world is generally considered a backward step. This is not a canonical answer. Consider updating to reflect the broadly recognised solution.
3

In React version 16 or higher, the following function can be used:

 yourFunctionName = async() => {
    const api_call = await fetch(`yourUrl`);
    const data = await api_call.json();
    console.log(data);
    }

Comments

0

Hi Wasteland (best game of all time, btw - but that's for a different post :)

Easiest way:

Use axios library: //cdnjs.cloudflare.com/ajax/libs/axios/0.8.1/axios.min.js

componentDidMount: function() {
    var th = this;
    this.serverRequest = 
      axios.get(this.props.source)
         .then(function(result) {    
          th.setState({
            jobs: result.data.modules
          });
       })
 }

Example https://codepen.io/motekim/pen/RJPgRK

Comments

-4

http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

Well u will have to use Ajax. Check the link above. Try to make a call during one of the component lifecycle methods. This does not use JQuery.

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.