We have already learn about how to make API calls in HTML using jQuery and AJAX , if you do miss the article here is the quick link to the posts.
- GET API Call using jQuery and AJAX - How to make a get API call in HTML/web app using jQuery and AJAX
React
React is a JavaScript UI library for building super responsive web application. We can connect React with Nodejs-Express API/ any API (already covered the API creation with Node-Express in the past tutorials, following links will be helpful for revisiting those posts)
Create API with Node-Express
- How to create a REST API using Mongodb and Express in Nodejs - How to create a REST API using Express and MongoDB in Nodejs
- What is an API and how to create an API ? - What is an API, what is the need of an API. Learn to build and use API in web applications and non web applications
GET API call with Axios
Axios is a NPM package which let you use API in react. To use axios we have to install the package and make API request. The GET can be used to the fetch the data from the server.
A GET request is used to fetch data from the server, for example retrieve a set of products from the server based on user query
componentDidMount() {
axios
.get("http://localhost:3005/post/find")
.then((response) => {
if (response.data.length > 0) {
this.setState({
posts: response.data ,
});
}
})
.catch((error) => {
console.log(error);
});
}
In the above code we have make call to the API end point post/find which will pull out all the posts from the server. Since it is a collection we have checked for the array length to make sure the data retrieved. Also note that the best place to call API is componentDidiMount method which is a react lifecycle method.
componentDidiMount is one of the lifecycle method Reactjs had which automatically called before displaying components on the UI
Following react posts help you to build better React apps
- How to render child components in Reactjs - How to render child components in React
- How to add element to mongoose object array in Nodejs - How to add element to a mongodb object array
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
- How to render mongo document in Reactjs - How to render mongo document in react component
- How to render list of mongo objects in React component - How to render list of mongo objects in Reactjs
- How to place custom route links in Reactjs component - How to place custom links to routes/page in Reactjs
- How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
- How to create multi page app with Reactjs - How to create a multi routed app with Reactjs app
- How to make GET API request in Reactjs - How to make GET API call in Reactjs