Using React Query with React Native Supabase Kit

React Query is the best React library for managing asynchronous data fetching in your applications. Learn how to use it with React Native Supabase.

Makerkit uses React Query for client-side data fetching. This allows you to fetch data from your Supabase database and display it on the client-side using an ergonomic API.

import { useQuery } from '@tanstack/react-query';
import { useSupabase } from '@kit/supabase';
import { Text, View } from 'react-native';
function TasksList(accountId: string) {
const client = useSupabase();
const { data, isLoading, error } = useQuery({
queryKey: ['tasks', accountId],
queryFn: async () => {
const { data, error } = await client
.from('tasks')
.select('*')
.eq('account_id', accountId)
.order('created_at', { ascending: false });
if (error) {
throw error;
}
return data;
}
});
if (isLoading) {
return <Text>Loading...</Text>;
}
if (error) {
return <Text>Error loading tasks</Text>;
}
return (
<View className={'flex gap-4'}>
{data.map(task => (
<View key={task.id}>
<Text>{task.title}</Text>
</View>
))}
</View>
);
}

By leveraging the useSupabase hook, you can access the Supabase DB data right from your React components.

Similarly, you can use React Query for mutations:

import { View } from 'react-native';
import { useMutation } from '@tanstack/react-query';
import { useSupabase } from '@kit/supabase';
import { Text, Button, Input } from '@kit/ui';
function CreateTaskForm() {
const client = useSupabase();
const mutation = useMutation({
mutationFn: async (data) => {
const { data, error } = await client
.from('tasks')
.insert({
title: data.title,
description: data.description,
account_id: data.accountId,
})
.select('*')
.single();
if (error) {
throw error;
}
return data;
},
});
const handleSubmit = async (data) => {
const { data, error } = await mutation.mutateAsync(data);
if (error) {
console.error(error);
}
};
return (
<View className="flex flex-col gap-4">
<Input type="text" name="title" />
<Input type="text" name="description" />
<Button onPress={handleSubmit}>
<Text>Create Task</Text>
</Button>
</View>
);
}