Last active
February 20, 2025 19:19
-
-
Save freddie-freeloader/19ee9d7273d2b215f2f2282dbb920ed5 to your computer and use it in GitHub Desktop.
Those Apollo types... Ugh...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type fetchMoar<Data> = | |
({ variables: { query, page, pageSize } }: | |
{ variables: { query: string | null, page: number, pageSize: number } }) => | |
Promise<{ error?: ApolloError, data: Data }> | |
type PaginationParams = { | |
query: string | null, | |
page?: number, | |
pageSize?: number | |
} | |
const letEmFetch = async <Data, Field>( | |
fn: fetchMoar<Data>, | |
accessData: (data: Data) => Field[], | |
{ query, pageSize = 100, page = 1 }: PaginationParams) | |
: Promise<Field[]> => { | |
const { error, data } = await fn({ variables: { query, page, pageSize } }); | |
if (error) { | |
throw error; | |
} | |
// Could do even more stuff here | |
return accessData(data); | |
} | |
// With letEmFetch | |
export const useElegantFetchMoreMeasurements = (pageSize: number = 5) => { | |
const { fetchMore } = useGetMeasurementOptionsQuery({ | |
skip: true | |
}); | |
const fetchMoreMeasurements = (query: string | null) => | |
letEmFetch(fetchMore, (data) => data.measurements.items, { query, pageSize }); | |
return fetchMoreMeasurements; | |
} | |
// Without letEmFetch | |
export const useNewButOldFetchMoreMeasurements = (pageSize: number = 5) => { | |
const { fetchMore } = useGetMeasurementOptionsQuery({ | |
variables: { page: 1, pageSize: pageSize }, | |
skip: true | |
}); | |
const fetchMoreMeasuremunts = async (query: string | null): Promise<MeasurementOption[]> => { | |
const queryResult = await fetchMore({ | |
variables: { | |
query: query, | |
} | |
}) | |
if (queryResult.error) { | |
throw queryResult.error; | |
} | |
return queryResult.data.measurements.items; | |
} | |
return fetchMoreMeasuremunts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment