Skip to content

Commit

Permalink
Implement refresh on pull.
Browse files Browse the repository at this point in the history
  • Loading branch information
jg210 committed Mar 7, 2024
1 parent ac74afb commit efb9290
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/Authorities.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Suspense } from "react";
import { FlatList, Text } from "react-native";

import { getAuthorities } from "./FSA";
import { useRefresh } from "./useRefresh";

const queryKey = ["authorities"];

Expand All @@ -16,12 +17,18 @@ const Fallback = () => <Text>loading...</Text>;
// https://react.dev/reference/react/Suspense suggests can use Suspense in same component
// that can suspend, but that doesn't work, so need a separate component.
const AuthoritiesImpl = () => {
const { data } = useSuspenseQuery({ queryKey, queryFn: getAuthorities });
const { data, refetch } = useSuspenseQuery({
queryKey,
queryFn: getAuthorities,
});
const { refreshing, onRefresh } = useRefresh(refetch);
return (
<FlatList
data={data}
renderItem={({ item }) => <Item name={item.name} />}
keyExtractor={(item) => item.localAuthorityId.toString()}
onRefresh={onRefresh}
refreshing={refreshing}
/>
);
};
Expand Down
3 changes: 2 additions & 1 deletion src/FSA.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ export const getAuthorities: () => Promise<LocalAuthority[]> = async () => {
"https://aws.jeremygreen.me.uk/api/fsa/localAuthority",
);
const json = (await authorities.json()) as unknown as LocalAuthorities;
return json.localAuthorities;
const { localAuthorities } = json;
return localAuthorities;
};
21 changes: 21 additions & 0 deletions src/useRefresh.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useState } from "react";

// Connects https://reactnative.dev/docs/flatlist onRefresh()/refreshing with refetch()
// returned by https://tanstack.com/query/v4/docs/framework/react/reference/useQuery
export function useRefresh<T>(refetch: () => Promise<T>) {
const [refreshing, setRefreshing] = useState(false);

async function onRefresh() {
setRefreshing(true);
try {
await refetch();
} finally {
setRefreshing(false);
}
}

return {
refreshing,
onRefresh,
};
}

0 comments on commit efb9290

Please sign in to comment.