Optimistic updates on paginated query #3388
Answered
by
yudyananda
yudyananda
asked this question in
Q&A
-
Anybody here use optimistic updates on paginated query? Here's my query // paginated profiles
const getProfiles = async (page: number, limit: number) => {
const { from, to } = getPagination(page, limit);
const { data, error, count } = await supabase
.from('profiles')
.select(`*, classes(id, name)`, { count: 'exact' })
.range(from, to)
.order('name', { ascending: false });
const profiles: ProfileProps[] = data;
const totalPage = count ? Math.ceil(count / limit) : 1;
const nextPage = page + limit;
const profileData = {
count,
profiles,
totalPage,
};
return profileData;
};
export function useProfiles(page: number, limit: number) {
return useQuery(['profiles', page], () => getProfiles(page, limit), {
refetchOnWindowFocus: false,
keepPreviousData: true,
});
} and this is the mutation part const profileUpdate = async (profile: ProfileUpdateProps) => {
const { data, error } = await supabase
.from('profiles')
.update({
assigned_as: profile.assigned_as,
classroom: profile.classroom,
})
.match({
id: profile.id,
});
if (error) throw new Error(error.message);
return data;
};
interface ContextProps {
profile: CamelizeProfileUpdateProps;
previousProfiles: CamelizeProfileUpdateProps[];
}
export function useProfileUpdate(profile: ProfileUpdateProps) {
const queryClient = useQueryClient();
return useMutation(() => profileUpdate(profile), {
onMutate: async () => {
await queryClient.cancelQueries(['profiles', profile.id]);
const previousProfiles = queryClient.getQueryData([
'profiles',
profile.id,
]);
queryClient.setQueryData(['profiles', profile.id], {
assigned_as: profile.assigned_as,
classroom: profile.classroom,
});
return {
previousProfiles,
assigned_as: profile.assigned_as,
classroom: profile.classroom,
};
},
onError: (context: ContextProps) => {
queryClient.setQueryData(
['profiles', context.profile.id],
context.previousProfiles
);
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onSettled: (newProfile: any) => {
queryClient.invalidateQueries(['profiles', newProfile?.id]);
},
});
} |
Beta Was this translation helpful? Give feedback.
Answered by
yudyananda
Mar 12, 2022
Replies: 1 comment
-
Never mind i just have to passed the ...
onSettled: (newProfile: any) => {
queryClient.invalidateQueries(['profiles', page, newProfile?.id]);
}, |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
yudyananda
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Never mind i just have to passed the
page
prop to theinvalidateQueries