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've seemingly have the fetch working, but I can't seem to save the data. 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 = async value => {
const response = await fetch( `https://api.microlink.io?url=${ value }`, {
cache: 'no-cache',
headers: {
'user-agent': 'WP Block',
'content-type': 'application/json'
},
method: 'GET',
redirect: 'follow',
referrer: 'no-referrer',
}).then(
returned => {
if (returned.ok) return returned;
throw new Error('Network response was not ok.');
}
);
let data = await response.json();
data = data.data;
props.setAttributes( { url: value } );
props.setAttributes( { title: data.title} );
};
return <div className={ props.className }>
<RichText
tagName="div"
placeholder={ __( 'Add URL here.' ) }
value={ props.attributes.url }
onChange={ onChangeURL }
/>
{ ! props.attributes.title ? __( 'Add URL' ) : <div> { props.attributes.title } </div> }
</div>;
}
Save function is pretty standard:
save: props => {
return (
<div className={ [props.className, 'o_microlink'].join( ' ' ) }>
<a href={ props.url}> { props.title } </a>
</div>
);
}
https://api.microlink.io?url= ${ value }
. Should that be in back-ticks? Is the$
supposed to be PHP?