react-query-est/App.js
2024-06-28 13:07:29 +02:00

93 lines
2.3 KiB
JavaScript

import React from "react";
import {SafeAreaView, View, Button, } from "react-native";
import NetInfo from "@react-native-community/netinfo";
import {useMutation, QueryClient, onlineManager} 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
},
mutations: {
cacheTime: 1000 * 60 * 60 * 24 * 2, // 2 days
},
},
});
onlineManager.setEventListener((setOnline) => {
return NetInfo.addEventListener((state) => {
setOnline(!!state.isConnected);
if (state.isConnected)
queryClient.resumePausedMutations();
});
});
const asyncStoragePersister = createAsyncStoragePersister({
storage: AsyncStorage,
});
// Define the "addTodo" mutation
queryClient.setMutationDefaults(["addTodo"], {
mutationFn: ({ page }) => {
return makeCall(page);
},
retry: Infinity,
networkMode: "offline",
});
function makeCall(page) {
console.log('mutations: ' + queryClient.getMutationCache().getAll().length);
console.log(queryClient.getMutationCache().getAll());
return fetch(`http://192.168.178.42:8080/${page}`)
.then(response => {
return response;
})
.catch(error => {
throw error;
});
}
function App() {
return (
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister: asyncStoragePersister }}
onSuccess={() => {
// resume mutations after initial restore from localStorage was successful
queryClient.resumePausedMutations()
}}
>
<SafeAreaView>
<View>
<ReqButton />
</View>
</SafeAreaView>
</PersistQueryClientProvider>
);
}
const ReqButton = () => {
const mutation = useMutation({ mutationKey: ["addTodo"] });
return (
<>
<Button
title={"Request"}
onPress={() => mutation.mutate({ page: "a" })}
/>
<Button title={'Resume'} onPress={() => queryClient.resumePausedMutations()}/>
<Button title={'clear'} onPress={() => queryClient.getMutationCache().clear()}/>
</>
);
};
export default App;