reactjsHow can I use React.js and AJAX to make API calls?
React.js and AJAX can be used together to make API calls. Here's an example of how to do this:
import React from 'react';
import axios from 'axios';
class App extends React.Component {
state = {
data: null
}
componentDidMount() {
const url = 'https://example.com/api';
axios.get(url)
.then(response => {
this.setState({ data: response.data });
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<div>
{this.state.data && <p>{this.state.data.message}</p>}
</div>
);
}
}
export default App;
The code above:
- Imports React and axios at the top of the file
- Defines the
Appclass which extendsReact.Component - Defines the
stateof the component, which is set to an empty object - Uses the
componentDidMountlifecycle method to make an AJAX call to the API - Uses the
setStatemethod to update thestatewith the data from the API call - Renders the data from the API call in the
rendermethod
Helpful links
More of Reactjs
- How do I create a zip file using ReactJS?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How do I zip multiple files using ReactJS?
- How can I become a React.js expert from scratch?
- How can I use ReactJS Zustand to manage state in my application?
- How do I obtain a license for ReactJS?
- How can I format a date in ReactJS?
- How do I install Yarn for React.js?
- How can I use Yup with ReactJS?
- How do I use Yup validation with ReactJS?
See more codes...