Next.js Discord

Discord Forum

onError not running when page is reloaded

Unanswered
Southern African anchovy posted this in #help-forum
Open in Discord
Southern African anchovyOP
I am trying to catch any images not loading by creating a component called SafeHtmlImge


This is the code

'use client'
import React, { FC, ReactNode, useState } from 'react';
const fallbackSrc = 'https://cdn......';

interface IImge {
    img: string,
    className?: string;
    children?: ReactNode;
};

const SafeHtmlImge: FC<IImge> = (props) => {
    const [imgSrc, setImgSrc] = useState(props.img)
    const onError = () => setImgSrc(fallbackSrc)
  
    return (
        <img 
            className={`${props.className}`}

            src={imgSrc ? imgSrc : fallbackSrc}
            onError={onError}

            alt=""
        />
    );
}


export { SafeHtmlImge}



When the page is reloaded the onError doesn't seem to run, but works fine if I nav to another page then back.

0 Replies