@vigilio/react-native-fetching
v0.0.1
Published
A data fetching library for React Native Expo with caching, retry, and background refetch support
Maintainers
Readme
@Vigilio/Preact-fetching (React Native Expo)
A data fetching hooks library for React Native Expo with caching, retry, and background refetch support.
Installation
npx expo install react
# Optional: for refetchOnReconnect support
npx expo install @react-native-community/netinfoGetting Started
useQuery: consume data fetching (GET)
import { useQuery } from "@vigilio/preact-fetching";
import { View, Text, ActivityIndicator } from "react-native";
async function getUsers(url: string, signal: AbortSignal) {
const response = await fetch("http://yourhost/api" + url, { signal });
const result = await response.json();
return result;
}
export function UsersScreen() {
const { isLoading, data, isSuccess, isError, refetch } = useQuery(
"/users",
getUsers,
);
if (isLoading) return <ActivityIndicator />;
if (isError) return <Text>Error loading users</Text>;
if (isSuccess) return <Text>{JSON.stringify(data)}</Text>;
return <View />;
}useQuery Options
const options = {
skipFetching: false, // skip fetch -> default false
placeholderData: null, // placeholder -> default null
transformData: null, // transform success data -> default null
staleTime: null, // refetch interval in seconds (1 = 1000ms)
refetchIntervalInBackground: false, // refetch when app returns to foreground (uses AppState)
onError: null, // callback on error (err) => {}
onSuccess: null, // callback on success (data) => {}
refetchOnReconnect: false, // refetch on network reconnect (requires @react-native-community/netinfo)
delay: null, // delay before fetch in seconds
retry: 3, // number of retries on error
retryDelay: null, // delay between retries in seconds
clean: true, // clean cache on refetch
isCaching: null, // enable in-memory caching (true or number for TTL ms)
isMemory: null, // enable memory storage (true or number for TTL ms)
};
const showUser = useQuery("/users", getUsers, options);useMutation: consume data fetching (POST/PUT/DELETE/PATCH)
import { useMutation } from "@vigilio/preact-fetching";
import { View, Text, TextInput, Pressable } from "react-native";
import { useState } from "react";
interface Body {
name: string;
}
async function addUser(url: string, body: Body, signal: AbortSignal) {
const response = await fetch("http://yourhost/api" + url, {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
signal,
});
return response.json();
}
export function AddUserScreen() {
const { mutate, isLoading } = useMutation("/users", addUser);
const [name, setName] = useState("");
function handleSubmit() {
mutate(
{ name },
{
onSuccess: (data) => console.log(data),
onError: (error) => console.log(error),
},
);
}
return (
<View>
<TextInput value={name} onChangeText={setName} placeholder="Name" />
<Pressable onPress={handleSubmit}>
<Text>{isLoading ? "Loading..." : "Send"}</Text>
</Pressable>
</View>
);
}mutateAsync
const { mutateAsync } = useMutation("/users", addUser);
async function handleSubmit() {
try {
const data = await mutateAsync({ name });
console.log(data);
} catch (err) {
console.error(err);
}
}Mutate Options
{
onSuccess?: (data) => {};
onError?: (error) => {};
transformData?: (data) => Data; // modify response data
}Using with Axios
import axios from "axios";
import { useQuery } from "@vigilio/preact-fetching";
const api = axios.create({ baseURL: "http://yourhost/api" });
interface User {
id: number;
name: string;
}
async function showUsers(url: string) {
const { data } = await api.get<User[]>(url);
return data;
}
const { isLoading, data } = useQuery("/users", showUsers);Dynamic Params (React Navigation)
import { useQuery } from "@vigilio/preact-fetching";
import { useRoute } from "@react-navigation/native";
import { View, Text, ActivityIndicator } from "react-native";
async function showById(url: string) {
const response = await fetch("http://yourhost/api" + url);
return response.json();
}
export function UserDetailScreen() {
const route = useRoute();
const { id } = route.params as { id: string };
const { isLoading, data, isSuccess, isError, error } = useQuery(
`/users/${id}`,
showById,
);
if (isLoading) return <ActivityIndicator />;
if (isSuccess) return <Text>{JSON.stringify(data)}</Text>;
if (isError) return <Text>{JSON.stringify(error)}</Text>;
return <View />;
}Platform Notes
- Cache/Memory: Both
cacheandmemoryare in-memory only (no persistent storage). For persistent caching, integrate@react-native-async-storage/async-storageseparately. - refetchIntervalInBackground: Uses React Native
AppStateto detect when the app returns to the foreground. - refetchOnReconnect: Requires
@react-native-community/netinfoas an optional dependency.
