fetching via fetch/ajax block data from third party

I’m trying to use fetch to grab information from a 3rd party API which is rate-limited. Instead of doing the API on the front-end I’m trying to use fetch to do the API call in the edit function. I’m not having any luck. Might someone suggest where I’m going wrong?

Attributes look like:

attributes: {
url: {
type: ‘string’,
selector: ‘.o_microlink’,
attribute: ‘href’,
default: ”,
},
title: {
type: ‘string’,
selector: ‘.o_microlink’,
default: ”,
},
}

Edit function looks like:

edit: props => {
const onChangeURL = value => {
fetch( ‘https://api.microlink.io?url= ${ url: value }’, {
body: JSON.stringify( data ),
cache: ‘no-cache’,
credentials: ‘same-origin’,
headers: {
‘user-agent’: ‘WP Block’,
‘content-type’: ‘application/json’
},
method: ‘GET’,
mode: ‘cors’,
redirect: ‘follow’,
referrer: ‘no-referrer’,
}).then(
response => {
if (response.ok) {
props.setAttributes({title: response.title});
return response.json();
}
throw new Error(‘Network response was not ok.’);
).catch(
error => {console.log(‘There has been a problem with your fetch operation: ‘, error.message);
}
);
props.setAttributes( { url: value } );
};
return <div className={ props.className }>
<RichText
tagName=”div”
placeholder={ __( ‘Add URL here.’ ) }
value={ attributes.url }
onChange={ onChangeURL }
/>
{ ! attributes.title ? __( ‘Add URL’ ) : <div> { attributes.title } </div> }
</div>;
}

Read more here:: fetching via fetch/ajax block data from third party

Leave a Reply

Your email address will not be published. Required fields are marked *