I am trying to see if a page/img successfully loads using javascript onload and onerror. I am attempting to read the status variable but am not able to do so when I assign the variable to read the status. I am attempting to use promises as outlined in the possible answers provides but still have some confusion.
const validateInput = (input) => {
const errors = {};
...
if(!(isImgURlValid(input)))
{
errors = `wrong image'`
}
...
return errors;
const isImgURlValid = (path) => {
let img = document.createElement('img');
img.src = path;
let valid
const promise = new Promise(resolve => {
const img = new Image();
img.onload = () => resolve({path, "status": 'ok'});
img.onerror = () => resolve({path, "status": 'error'});
img.src = path;
});
promise.then(function(val) {
console.log(val);
valid = val.status
});
console.log (valid)
}
//when I use async, my render functions no long render the errors properly
export const renderImgUrlInput = ({ input, label, type, size, required, meta: { touched, error } }) => (
<div className={
cs('form-group', size, {
'has-error': touched && error,
'required-input' : required
})
}>
<label className="control-label" htmlFor={input.name}>{label}</label>
<input {...input} placeholder={required ? 'Required' : ''} className="form-control" />
{touched && error &&
<span className="help-block">{error}</span>
}
{touched && !error &&
<h1 className="help-block">{error} 'Image worked'</h1>
}
</div>
)