Reputation: 1450
We have made a simple application that supports CRUD operations on a student model(Get Student by ID, Delete Student by ID etc). Can someone help with how to make a simple restful api call to the endpoint(http://ip:port/allstudents) and render the obtained json format in React UI? My code is as follows:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
Getfunction() {
<a href="http://www.stackoverflow.com/">
<button>b1</button>
</a>
}
render() {
return (
<div>
<button id='b1'
style={{fontSize: 20, color: 'green'}}
onClick={() => this.Getfunction()}>
Get!
</button>
);
}
}
export default App;
Where can I put my restful api call to query and how exactly?
Upvotes: 2
Views: 5491
Reputation: 24140
I would suggest you to make api call in life cycle method componentDidMount
and when api call returns some data set it to your state and let your user interface update accordingly.
E.g your api call method may be like this -
ApiCall() {
return $.ajax({
url: 'http://ip:port/allstudents',
type: 'GET',
}).fail((responseData) => {
if (responseData.responseCode) {
console.error(responseData.responseCode);
}
});
}
After new data is fetched from server set the state with new data
this.setState({data:newDataFromServer});
Basically above call will return you a jquery promise which you can use later.
Now in what ever method you want to make ApiCall just use like this -
class App extends Component {
constructor() {
this.state = {
data : []
}
}
componentDidMount()
{
this.getFunction();
}
getFunction = () => {
this.ApiCall()
.then(
function(data){
console.log(data);
// set the state here
this.setState({data:data});
},
function(error){
console.log(error);
}
);
}
render() {
return (
<div>
<button id='b1'
style={{fontSize: 20, color: 'green'}}
onClick={() => this.Getfunction()}>
Get!
</button>
{/* Now render your data here using jsx if it is array iterate over it */}
</div>
);
}
}
Upvotes: 3