react-query-est/App.js

107 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-05-31 16:19:51 +02:00
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
*/
import React from "react";
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Button,
} from "react-native";
import { useNetInfoInstance } from "@react-native-community/netinfo";
import {
useQuery,
useMutation,
useQueryClient,
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query";
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
import AsyncStorage from "@react-native-async-storage/async-storage";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
2024-05-31 16:57:13 +02:00
mutations: {
cacheTime: Infinity,
retry: true,
},
2024-05-31 16:19:51 +02:00
},
});
const asyncStoragePersister = createAsyncStoragePersister({
storage: AsyncStorage,
});
// Define the "addTodo" mutation
queryClient.setMutationDefaults(["addTodo"], {
mutationFn: ({ page }) => {
return makeCall(page);
},
retry: 3,
});
function makeCall(page) {
return fetch(`http://10.0.2.2:8080/${page}`)
.then(response => {
return response;
})
.catch(error => {
console.log(error);
console.log(12);
});
}
function App() {
return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister: asyncStoragePersister }}
2024-05-31 16:58:16 +02:00
onSuccess={() => {
queryClient.resumePausedMutations().then(() => {
queryClient.invalidateQueries();
});
}}
2024-05-31 16:19:51 +02:00
>
<SafeAreaView>
<View>
<ReqButton />
</View>
</SafeAreaView>
</PersistQueryClientProvider>
);
}
const ReqButton = () => {
const mutation = useMutation({ mutationKey: ["addTodo"] });
2024-05-31 16:49:47 +02:00
const query = useQuery({ queryKey: ["todos"], queryFn: () => makeCall("a") });
2024-05-31 16:19:51 +02:00
return (
2024-05-31 16:49:47 +02:00
<>
<Button
title={"Request"}
onPress={() => mutation.mutate({ page: "a" })}
/>
<Text>{query.data && query.data.toString() || ''}</Text>
</>
2024-05-31 16:19:51 +02:00
);
};
export default App;