Prevent wrong initial color on navigation on the same route

This commit is contained in:
jeffvli 2023-07-21 18:51:37 -07:00
parent 48eaddbeda
commit 853770ea8e
7 changed files with 62 additions and 38 deletions

View file

@ -1,11 +1,15 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { FastAverageColor } from 'fast-average-color';
export const useFastAverageColor = (
src?: string | null,
srcLoaded?: boolean,
aglorithm?: 'dominant' | 'simple' | 'sqrt',
) => {
export const useFastAverageColor = (args: {
algorithm?: 'dominant' | 'simple' | 'sqrt';
id?: string;
src?: string | null;
srcLoaded?: boolean;
}) => {
const { algorithm, src, srcLoaded, id } = args;
const idRef = useRef<string | undefined>(id);
const [color, setColor] = useState<string | undefined>(undefined);
useEffect(() => {
@ -13,7 +17,7 @@ export const useFastAverageColor = (
if (src && srcLoaded) {
fac.getColorAsync(src, {
algorithm: aglorithm || 'dominant',
algorithm: algorithm || 'dominant',
ignoredColor: [
[255, 255, 255, 255, 90], // White
[0, 0, 0, 255, 30], // Black
@ -22,10 +26,12 @@ export const useFastAverageColor = (
mode: 'precision',
})
.then((color) => {
idRef.current = id;
return setColor(color.rgb);
})
.catch((e) => {
console.log('Error fetching average color', e);
idRef.current = id;
return setColor('rgba(0, 0, 0, 0)');
});
} else if (srcLoaded) {
@ -35,7 +41,7 @@ export const useFastAverageColor = (
return () => {
fac.destroy();
};
}, [aglorithm, srcLoaded, src]);
}, [algorithm, srcLoaded, src, id]);
return color;
return { color, colorId: idRef.current };
};