Learn about React Query
useMutation #
It uses other methods except for GET.
// Create a mutation for adding a user
const {
mutate,
mutateAsync,
isLoading: isAddingUser,
error: addError
} = useMutation(addUser);
const handleAddUser = async () => {
const data = await mutateAsync({
first_name: 'React Query',
last_name: 'Rules!'
});
console.log('This was an async mutation!');
console.log(data);
refetch();
};
QueryClient #
It can update the data without using the refetch() function. New data can be pushed to old data through setQueryData, so the number of fetches will be reduced.
// setQueryData(queryKey, oldData => newData)
const queryClient = useQueryClient();
const handleAddUser = async () => {
const newUser = await mutateAsync({
first_name: 'React Query',
last_name: 'Rules!'
});
queryClient.setQueryData('users', oldData => ({
...oldData,
data: [newUser, ...oldData.data]
}));
}
useInfiniteQuery #
It seems only working for the fetch data mention about pages.
const fetchInfiniteUsers = async ({ pageParam = 1 }) => {
const response = await fetch(`https://reqres.in/api/users?page=${pageParam}`);
if (!response.ok) {
throw new Error('Something went wrong!');
}
return response.json();
};
const {
data,
isLoading,
isFetching,
fetchNextPage,
hasNextPage,
error
} = useInfiniteQuery('users', fetchInfiniteUsers, {
getNextPageParam: (lastPage, pages) => {
if (lastPage.page < lastPage.total_pages) return lastPage.page + 1;
return false;
}
});