Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add useFetchState composable (#1178)

Olga Bulat8db30eaa83f5
diff --git a/src/composables/use-fetch-state.ts b/src/composables/use-fetch-state.ts
new file mode 100644
index 000000000..92e78adc2
--- /dev/null
+++ b/src/composables/use-fetch-state.ts
@@ -0,0 +1,112 @@
+import { computed, reactive, Ref, ref, watch } from '@nuxtjs/composition-api'
+
+export interface FetchState {
+ isFetching: boolean
+ fetchingError: null | string
+ canFetch?: boolean
+ hasStarted?: boolean
+ isFinished?: boolean
+}
+
+/* Constants */
+
+/**
+ * Statuses of requests:
+ * - `idle`: the current request has never been sent yet, for example,
+ * on the first app load, or after a change in search filters or search term.
+ * - `fetching`: the request was sent, but no response was received yet.
+ * - `success`: a successful response was received for the current request.
+ * - `finished`: for multi-page requests, this is true when no more pages are left.
+ * - `error`: an error response was received.
+ */
+const statuses = Object.freeze({
+ IDLE: 'idle',
+ FETCHING: 'fetching',
+ SUCCESS: 'success',
+ ERROR: 'error',
+ FINISHED: 'finished',
+} as const)
+
+type Status = typeof statuses[keyof typeof statuses]
+/**
+ * When one of these statuses is received, the fetchError is set to `null` in a watcher.
+ */
+const nonErrorStatuses: Status[] = [
+ statuses.IDLE,
+ statuses.FETCHING,
+ statuses.SUCCESS,
+]
+/**
+ * With these statuses, it is possible to send the same request for a new page.
+ * This can help debounce requests and prevent racing states.
+ */
+const canFetchStatuses: Status[] = [statuses.IDLE, statuses.SUCCESS]
+
+/* Composable */
+
+export const useFetchState = (initialState = statuses.IDLE) => {
+ const fetchStatus: Ref<Status> = ref(initialState)
+ const fetchError: Ref<string | null> = ref(null)
+
+ watch(fetchStatus, () => {
+ if (nonErrorStatuses.includes(fetchStatus.value)) {
+ fetchError.value = null
+ }
+ })
+ const reset = () => {
+ fetchStatus.value = statuses.IDLE
+ }
+ const startFetching = () => {
+ fetchStatus.value = statuses.FETCHING
+ }
+ /**
+ * Called when any response is received. For an error response,
+ * pass the errorMessage string as a parameter.
+ * @param errorMessage - the message to show for response error.
+ */
+ const endFetching = (errorMessage?: string) => {
+ if (errorMessage) {
+ fetchStatus.value = statuses.ERROR
+ fetchError.value = errorMessage
+ } else {
+ fetchStatus.value = statuses.SUCCESS
+ }
+ }
+ const setFinished = () => {
+ fetchStatus.value = statuses.FINISHED
+ }
+
+ /**
+ * Whether the current request has been sent. This can be useful for displaying
+ * initial search page with a blank search term, such as for a provider search page.
+ */
+ const hasStarted = computed(() => fetchStatus.value !== statuses.IDLE)
+ const isFetching = computed(() => fetchStatus.value === statuses.FETCHING)
+ /**
+ * Whether a new request for the same parameters with a new page can be sent.
+ * Use this to ensure that prevent racing requests.
+ */
+ const canFetch = computed(() => canFetchStatuses.includes(fetchStatus.value))
+ /**
+ * Used for paginated requests, `isFinished` means there are no more pages left.
+ */
+ const isFinished = computed(() => fetchStatus.value === statuses.FINISHED)
+ const fetchingError = computed(() => fetchError.value)
+
+ const fetchState: FetchState = reactive({
+ hasStarted,
+ isFetching,
+ canFetch,
+ isFinished,
+ fetchingError,
+ })
+
+ return {
+ fetchState,
+
+ startFetching,
+ endFetching,
+ setFinished,
+ reset,
+ }
+}
diff --git a/src/store/types.ts b/src/store/types.ts
index beab30130..0ae85fc63 100644
--- a/src/store/types.ts
+++ b/src/store/types.ts
@@ -1,8 +1,7 @@
-import type { SupportedSearchType } from '~/constants/media'
-
/**
* The search result object
*/
+import type { FetchState } from '~/composables/use-fetch-state'
type FrontendMediaType = MediaDetail['frontendMediaType']
export interface MediaResult<
@@ -132,17 +131,6 @@ export interface Filters {
}
export type FilterCategory = keyof Filters
-export interface FetchState {
- isFetching: boolean
- fetchingError: null | string
- isFinished?: boolean
-}
-
-export interface SearchState {
- searchType: SupportedSearchType
- query: Query
-}
-
export type MediaStoreResult<T extends FrontendMediaType> = MediaResult<
Record<MediaDetail['id'], T>
>
@@ -152,16 +140,10 @@ export interface MediaState {
audio: MediaStoreResult<'audio'>
image: MediaStoreResult<'image'>
}
- mediaFetchState: {
+ fetchState: {
audio: FetchState
image: FetchState
}
audio: AudioDetail
image: ImageDetail
}
-
-export interface MediaFetchState {
- isFetching: boolean
- fetchingError: string | null
- isFinished?: boolean
-}
diff --git a/test/unit/specs/composables/use-fetch-state.spec.ts b/test/unit/specs/composables/use-fetch-state.spec.ts
new file mode 100644
index 000000000..67d8f18f3
--- /dev/null
+++ b/test/unit/specs/composables/use-fetch-state.spec.ts
@@ -0,0 +1,59 @@
+import { useFetchState } from '~/composables/use-fetch-state'
+
+describe('useFetchState', () => {
+ it('should use the default values', () => {
+ const fetchState = useFetchState()
+ expect(fetchState.fetchState).toEqual({
+ isFetching: false,
+ isFinished: false,
+ fetchingError: null,
+ canFetch: true,
+ hasStarted: false,
+ })
+ })
+ it('should start fetching', () => {
+ const fetchState = useFetchState()
+ fetchState.startFetching()
+
+ expect(fetchState.fetchState).toEqual({
+ isFetching: true,
+ isFinished: false,
+ fetchingError: null,
+ canFetch: false,
+ hasStarted: true,
+ })
+ })
+ it('should end fetching with success', () => {
+ const fetchState = useFetchState()
+ fetchState.endFetching()
+ expect(fetchState.fetchState).toEqual({
+ isFetching: false,
+ isFinished: false,
+ fetchingError: null,
+ canFetch: true,
+ hasStarted: true,
+ })
+ })
+ it('should end fetching with error', () => {
+ const fetchState = useFetchState()
+ fetchState.endFetching('Server Error')
+ expect(fetchState.fetchState).toEqual({
+ isFetching: false,
+ isFinished: false,
+ fetchingError: 'Server Error',
+ canFetch: false,
+ hasStarted: true,
+ })
+ })
+ it('should set fetching to finished', () => {
+ const fetchState = useFetchState()
+ fetchState.setFinished()
+ expect(fetchState.fetchState).toEqual({
+ isFetching: false,
+ isFinished: true,
+ fetchingError: null,
+ canFetch: false,
+ hasStarted: true,
+ })
+ })
+})