Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consuming a RESTful service in Reactjs

im starting with reactjs and i want to make a GET request to a RESTful service, here is my code, can anyone help me please?

render: function() {
$.ajax({
  url: "http://rest-service.guides.spring.io/greeting"
}).then(function(data) {
  $('.greeting-id').append(data.id);
  $('.greeting-content').append(data.content);
return <div style="background-color: #ffffff">
                    <p class="greeting-id">The ID is </p>
                    <p class="greeting-content">The content is </p>

                </div>;        
    }

}

i already load Jquery in the html with react, but i still cant make it work, i'm missing something important? or there is a better way to do this? i dont want to use another extra thing, just react and Jquery, or is something more necesary?

Thank you for all the help.

like image 427
Tristán Belmont Avatar asked Jul 22 '15 15:07

Tristán Belmont


People also ask

Which library can be used to consume REST service using React?

In React, there are various ways we can consume REST APIs in our applications, these ways include using the JavaScript inbuilt fetch() method and Axios which is a promise-based HTTP client for the browser and Node. js.

What is restful API in React?

On the other hand, React is one of the most familiar front-end JavaScript libraries used for web applications. Businesses can gain benefits by consuming React REST APIs. It will not only enhance user experience but also allow developers to create large web applications that can change data without reloading the page.

Why we use REST API in react JS?

When a request is made via a REST API, it sends a representation of the resource's current state to the requester or endpoint. This state representation can take the form of JSON (JavaScript Object Notation), XML, or HTML.


1 Answers

Make your request in the componentDidMount method and use the setState method to assign the data returned by RESTful service to your component's state. In render method you can access it through this.state.greetingId and this.state.greetingContent properties:

componentDidMount: function(){
    $.ajax({
      url: "http://rest-service.guides.spring.io/greeting"
    }).then(function(data) {
        this.setState({
            greetingId: data.id,
            greetingContent: data.content
        });
    }
)},
render: function() {
    return <div style="background-color: #ffffff">
                <p class="greeting-id">The ID is {this.state.greetingId}</p>
                <p class="greeting-content">The content is {this.state.greetingContent}</p>
            </div>;        
}

Refer to the following link for details: https://facebook.github.io/react/tips/initial-ajax.html

like image 162
const314 Avatar answered Sep 20 '22 23:09

const314