I want to retrieve an array from my db using axios and display it in react component. I have used componentDidMount() lifecycle method with async/await syntax as follows:
state = {
products: []
}
async componentDidMount() {
const res= await axios.get(http://santacruz.clickysoft.net/api/public/home-product)
.then(res => this.setState({products: res.data.products})
.catch(err => console.log(err));
}
The return statement of the class component is as follows:
return (
<div className="wwd animated" data-animation="bounceInLeft">
<div className="wwd-slider">
<div className="container-fluid">
<div className="row">
<div className="col-md-12 nlrp">
<div className="owl-carousel owl-theme">
{
this.state.product.map( product =>
<div className="item">
<img src="images/p-01.png" className="img-fluid" />
<div className="wwd-over">
<a href="#">{product.product_name}</a>
<p>{product.info}</p>
</div>
</div>
)}
}
</div>
</div>
</div>
</div>
</div>
</div>
);
When I run this, it works fine, the state is updated and I can see all products in it but it seems that because every time the state updates, the components re renders itself and my element alignment on the web page is completely disturbed.
I want the the request to wait until all elements are fetched from db and then map it on the state only once. Can somebody tell me how to achieve this?
When I hard code all 14 items of the array in state, I can the desired aligned carousel view as follows:
But when I fetch data from backend using axios in the same map function, everything gets disturbed.
Can anyone why is this happning?


this.setStateincomponentDidMount?setState, you might have noticed the same issue :). It helps to only change one thing at a time when debugging, but I probably would have done the same thing :D.