Loading data via REST API - markhowellsmead/helpers GitHub Wiki
CAUTION: if there are 10'000 posts in the database, then all 10'000 will be loaded. 😁
This code is within a component structure: setData
etc. are state methods from useState
.
import apiFetch from '@wordpress/api-fetch';
// …
const updateData = () => {
let allData = [];
const query = 'orderby=id&order=asc&status=publish';
const fetchAllEntries = (page = 1) => {
const completeQuery = `${query}&page=${page}&per_page=30`;
let totalPages = 0;
apiFetch({ path: `/wp/v2/posts/?${completeQuery}`, method: 'GET', parse: false })
.then((res) => {
totalPages = res.headers.get('X-WP-TotalPages');
return res.json();
})
.then((res) => {
allData = [...allData, ...res];
if (page < totalPages) {
fetchAllEntries(page + 1);
} else {
setData(allData);
setLoading(false);
}
})
.catch((err) => {
setError(err);
setLoading(false);
});
};
fetchAllEntries();
};
Add an empty container to the page with a data attribute to specify the path from which the data should be fetched.
-
data-fill-from-api
: Partial path, from which REST API endpoint the HTML should be collected. This will be prefixed with the usual REST API URL (e.g. https://www.example.com/wp-json/). -
data-api-validation-code
: Only display the HTML if the API returns this code (e.G.facilities_status_count
).
<div class="facility-status-wrap" data-fill-from-api="markhowellsmead/v1/facilities/statuscount/html/" data-api-validation-code="facilities_status_count"></div>
(function($) {
var apiURL;
/**
* Get the base URL of the REST API
* @return {string} The base URL of the REST API
*/
var getApiUrl = function() {
$api_link = $('link[rel="https://api.w.org/"]');
if ($api_link.length === 1) {
apiURL = $api_link.attr('href');
if (!apiURL || apiURL === '') {
window.console.error('No REST API URL available :(');
return false;
}
return apiURL;
}
return false;
};
apiURL = getApiUrl();
if (apiURL !== '') {
/**
* Call the REST API using the base apiURL and the part-URL from an element's
* data-fill-from-api attribute. The element's data-api-validation-code value
* can be checked against the response_data.code to make sure that no unexpected
* HTML is displayed on the website.
*/
$(document).on('ready.data-from-api', function() {
$('[data-fill-from-api][data-api-validation-code]').each(function() {
var $this = $(this);
var url = $(this).data('fill-from-api');
var validation_code = $(this).data('api-validation-code');
if (validation_code !== '' && url !== '') {
$(this).addClass('is--waiting');
$.ajax({
cache: false,
dataType: 'json',
url: apiURL + url,
success: function(response_data) {
$(this).removeClass('is--waiting');
if (response_data.code && response_data.data && response_data.data.result && response_data.code === validation_code) {
$this.html(response_data.data.result);
if ($this.html() === '') {
$this.addClass('is--empty');
} else {
$this.addClass('is--filled');
}
if(response_data.data.css_class){
$this.addClass(response_data.data.css_class);
}
}
},
error: function() {
$(this).removeClass('is--waiting');
$this.addClass('response-error');
}
});
}
});
});
}
}(jQuery));