Basically I load my homepage and one of my components is the following:
import React, {Component} from 'react';
class BlogPostsWidget extends Component {
render() {
$.ajax({
type: "GET",
url: 'https://example.com/wp-json/wp/v2/posts?filter[orderby]=asc&filter&per_page=3&categories=1,2,3,11,258,378,447',
dataType: 'json',
success: function(data) {
data.forEach(function(post) {
$( '.blog__body' ).append( '<div class="col-md-4"><div class="blog__body__article"><a target="_blank" href="' + post.link + '"><img class="card-img-top img-responsive lazy" src="' + post.ccw_thumbnail + '"></a><h2 class="bold text-center card-title">' + post.title.rendered + '</h2><div class="short-border"></div>' + post.excerpt.rendered + '<a target="_blank" class="black-link" href="' + post.link + '">READ MORE <i class="fa fa-chevron-right"></i></a></div>' );
});
}
});
return (
<div className="blog">
<div className="blog__body">
</div>
</div>
);
}
}
export default BlogPostsWidget;
On initial page load everything is working fine. However if i click on my logo to re-render my homepage my Ajax call is firing again causing the same 3 blog posts to be loaded in after my already rendered ones
How do I make sure my Ajax script runs only once?
Use componentDidMount lifecycle method, and put the ajax call inside that. It will get called only once just after the component rendering.
From DOC:
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.