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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With