mirror of
https://github.com/bitsocialnet/5chan.git
synced 2026-08-03 07:41:04 +02:00
Update use-fetch-gif-first-frame.ts
This commit is contained in:
@@ -1,16 +1,14 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
import localForageLru from '@plebbit/plebbit-react-hooks/dist/lib/localforage-lru/index.js';
|
||||||
|
|
||||||
const GIF_FRAME_CACHE_KEY = 'gifFrameCache';
|
const gifFrameDb = localForageLru.createInstance({ name: 'plebchanGifFrames', size: 500 });
|
||||||
|
|
||||||
const getCachedGifFrame = (url: string): string | null => {
|
const getCachedGifFrame = async (url: string): Promise<string | null> => {
|
||||||
const cache = JSON.parse(localStorage.getItem(GIF_FRAME_CACHE_KEY) || '{}');
|
return await gifFrameDb.getItem(url);
|
||||||
return cache[url] || null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const setCachedGifFrame = (url: string, frameUrl: string): void => {
|
const setCachedGifFrame = async (url: string, frameUrl: string): Promise<void> => {
|
||||||
const cache = JSON.parse(localStorage.getItem(GIF_FRAME_CACHE_KEY) || '{}');
|
await gifFrameDb.setItem(url, frameUrl);
|
||||||
cache[url] = frameUrl;
|
|
||||||
localStorage.setItem(GIF_FRAME_CACHE_KEY, JSON.stringify(cache));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchImage = (url: string): Promise<ArrayBuffer> => {
|
export const fetchImage = (url: string): Promise<ArrayBuffer> => {
|
||||||
@@ -75,7 +73,7 @@ const useFetchGifFirstFrame = (url: string | undefined) => {
|
|||||||
|
|
||||||
const fetchFrame = async () => {
|
const fetchFrame = async () => {
|
||||||
try {
|
try {
|
||||||
const cachedFrame = getCachedGifFrame(url);
|
const cachedFrame = await getCachedGifFrame(url);
|
||||||
if (cachedFrame) {
|
if (cachedFrame) {
|
||||||
if (isActive) setFrameUrl(cachedFrame);
|
if (isActive) setFrameUrl(cachedFrame);
|
||||||
return;
|
return;
|
||||||
@@ -85,7 +83,7 @@ const useFetchGifFirstFrame = (url: string | undefined) => {
|
|||||||
const objectUrl = URL.createObjectURL(blob);
|
const objectUrl = URL.createObjectURL(blob);
|
||||||
if (isActive) {
|
if (isActive) {
|
||||||
setFrameUrl(objectUrl);
|
setFrameUrl(objectUrl);
|
||||||
setCachedGifFrame(url, objectUrl);
|
await setCachedGifFrame(url, objectUrl);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load GIF frame:', error);
|
console.error('Failed to load GIF frame:', error);
|
||||||
@@ -95,7 +93,6 @@ const useFetchGifFirstFrame = (url: string | undefined) => {
|
|||||||
|
|
||||||
fetchFrame();
|
fetchFrame();
|
||||||
|
|
||||||
// Cleanup function to avoid setting state on unmounted component
|
|
||||||
return () => {
|
return () => {
|
||||||
isActive = false;
|
isActive = false;
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user