I\'ve been building a Gutenberg Block that sends a GET
request to the Woocommerce REST API.
It is composed of a text input
that receives an ID of a product and fetches it to the Woocommerce REST API. It also has a button
that fires a function to fetch the product with the API.
The issue with the GET Requests
The fetching works well, but it keeps sending multiple GET
requests, even when I do not click the button to fire the function. Simply clicking the input sends multiple requests when I only need one everytime I change the ID and click the button.
I\'m importing WooCommerceRestApi
from "@woocommerce/woocommerce-rest-api"
and use Node.js.
The code
This is the first part of the edit function:
const edit = ({ attributes, setAttributes }) => {
const blockProps = useBlockProps();
// Wrapped the WooCommerce.get() function in a function named `fetchingId` to call it with a button
const fetchingId = async (id) => {
// The WooCoommerce.get() function
const response = await WooCommerce.get(`products/${id}`)
.then((response) => {
console.log(response.data);
setAttributes({ price: response.data.price });
setAttributes({ name: response.data.name });
})
.catch((error) => {
console.log(error.response.data);
setAttributes({ price: \'\' });
setAttributes({ name: \'\' });
});
}
...
}
This is another part of the function: an input that updates the Product ID
that is used for the GET
request and a button linked to the fetchingId()
function.
return <div {...blockProps}>
<div class="wrapper-input" >
<TextControl
label={__(\'ID du Produit\', \'ingredient-unique\')}
value={attributes.id}
onChange={(val) => setAttributes({ id: val })}
className=\'control-id\'
/>
</div>
<button onclick={fetchingId(attributes.id)}>Chercher le produit</button>
...
</div>;