You can fetch data on component mount in React by using the componentDidMount
lifecycle method. Inside this method, you can make an API call or fetch data from a server using fetch
or your preferred HTTP client library. Here's an example of fetching data on component mount:
import React, { Component } from 'react';
class MyComponent extends Component {
state = {
data: []
};
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }))
.catch(error => console.error('Error fetching data:', error));
}
render() {
return (
<div>
{this.state.data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
}
export default MyComponent;
In this example, the componentDidMount
method is used to fetch data from an API when the component mounts. The fetched data is then stored in the component's state, triggering a re-render to display the fetched data in the component.