EntityStore: support staleTime option (automatically fetch)

develop^2
Alex Gleason 2023-03-09 14:20:04 -06:00
rodzic d883f2f5bd
commit a3b1f541bc
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
3 zmienionych plików z 20 dodań i 0 usunięć

Wyświetl plik

@ -1,3 +1,5 @@
import { useEffect } from 'react';
import { getNextLink, getPrevLink } from 'soapbox/api';
import { useApi, useAppDispatch, useAppSelector } from 'soapbox/hooks';
@ -17,6 +19,11 @@ type EntityPath = [
interface UseEntitiesOpts<TEntity> {
/** A parser function that returns the desired type, or undefined if validation fails. */
parser?: (entity: unknown) => TEntity | undefined
/**
* Time (milliseconds) until this query becomes stale and should be refetched.
* It is 1 minute by default, and can be set to `Infinity` to opt-out of automatic fetching.
*/
staleTime?: number
}
/** A hook for fetching and displaying API entities. */
@ -65,6 +72,7 @@ function useEntities<TEntity extends Entity>(
prev: getPrevLink(response),
fetching: false,
error: null,
lastFetchedAt: new Date(),
}));
} catch (error) {
dispatch(entitiesFetchFail(entityType, listKey, error));
@ -91,6 +99,15 @@ function useEntities<TEntity extends Entity>(
}
};
const staleTime = opts.staleTime ?? 60000;
const lastFetchedAt = list?.state.lastFetchedAt;
useEffect(() => {
if (!isFetching && (!lastFetchedAt || lastFetchedAt.getTime() + staleTime <= Date.now())) {
fetchEntities();
}
}, [endpoint]);
return {
entities,
fetchEntities,

Wyświetl plik

@ -27,6 +27,8 @@ interface EntityListState {
error: any
/** Whether data for this list is currently being fetched. */
fetching: boolean
/** Date of the last API fetch for this list. */
lastFetchedAt: Date | undefined
}
/** Cache data pertaining to a paritcular entity type.. */

Wyświetl plik

@ -31,6 +31,7 @@ const createList = (): EntityList => ({
prev: undefined,
fetching: false,
error: null,
lastFetchedAt: undefined,
},
});