0

I'm creating a client side search for blog articles and I'm displaying the results in a card with an image. I think a pretty straight forward use case. I'm using Next.js and their image component to load the images.

I am doing real time typing filters on the results so as you type the result cards change. A problem I am having is that as you type and replace the cards along with a new image, the browser is still loading the last image and causes a backlog of images being loaded.

I'm wondering if there is a way to cancel the requests of the images that have just been removed. An alternative would be to debounce the filtering but I'd like to be as performant as possible.

Here's some of my code.

Search Cards

import Image from 'next/image';
import styles from './SearchCard.module.scss';

export default function SearchCard({ data, onClick }: any) {
    return (
        <a className={styles.searchCard} onClick={onClick}>
            <Image
                src={data.image}
                width={289}
                height={152}
                alt=""
                placeholder="blur"
                blurDataURL={data.placeholderImage}
            />

            <h3>{data.title}</h3>
            <p>{data.description}</p>
        </a>
    );
}

Real time filtering

const searchInitiatives = (value: string) => {
   const results = initiativesDb.search(value);
   const foundInitiatives = results.map((el: any) => el.item);
   value ? setInitiatives(foundInitiatives) : setInitiatives(defaultInitiatives);
};

Search Results


initiatives
    .filter((_, i) => i < INITIATIVES_MAX)
    .map((el, i) => (
         <SearchCard key={el.guid} onClick={handleSelect} data={el} />
    ))}

Image Loading Backlog

This happens as your type and the results are updated/filtered based on your query. these images in this example are small but it does have an effect on latest image load times. especially when you simulate slow connections.

enter image description here

user2249567
  • 394
  • 4
  • 9
  • You're probably better off debouncing the results filtering, as you mentioned, and as suggested in this related question [How do I abort image load requests without using window.stop()](https://stackoverflow.com/questions/6929662/how-do-i-abort-image-img-load-requests-without-using-window-stop). – juliomalves Aug 15 '21 at 12:10

0 Answers0