Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,5 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

/.idea
9 changes: 9 additions & 0 deletions app/components/AddHotelForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";
import * as React from "react";
import { Button, Paper, Stack, TextInput, Title } from "@mantine/core";
import {useEffect} from "react";

export interface HotelFormValues {
name: string;
Expand Down Expand Up @@ -28,6 +29,14 @@ export function AddHotelForm(props: AddHotelFormProps) {
}
};

useEffect(() => {
if (!isSubmitting) {
setName("");
setDescription("Lorem ipsum description.");
setPrice("7999");
}
}, [isSubmitting]);

return (
<Paper p="lg" withBorder>
<Title order={2}>Add new hotel</Title>
Expand Down
31 changes: 24 additions & 7 deletions app/components/HotelsGridInfinite.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"use client";
import * as React from "react";
import { Button, Center, Loader, SimpleGrid, Stack, Text } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import {useInfiniteQuery, useQuery} from "@tanstack/react-query";
import { HotelDTO } from "../types";
import { Hotel } from "./Hotel";
import {useIntersection} from "@mantine/hooks";
import {useEffect} from "react";

export function HotelsGridInfinite() {
// @TODO: implement infinite scroll using useInfiniteQuery
Expand All @@ -14,17 +16,31 @@ export function HotelsGridInfinite() {
// next: number;
// }>
// read more: https://tanstack.com/query/latest/docs/framework/react/guides/infinite-queries
const { data, isPending, isError } = useQuery<HotelDTO[]>({
const { entry, ref } = useIntersection();
const { data, isPending, isError, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: ["hotels-pages"],
queryFn: async () => {
const res = await fetch(`http://localhost:8080/hotels`);
queryFn: async ({
pageParam,
}): Promise<{
data: HotelDTO[];
next: number;
}> => {
const res = await fetch(`http://localhost:8080/hotels?_page=${pageParam}&_per_page=5`);
if (!res.ok) {
throw new Error("Failed to fetch");
}
return await res.json();
},
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.next,
});

useEffect(() => {
if (entry?.isIntersecting && hasNextPage) {
fetchNextPage();
}
}, [entry?.isIntersecting, hasNextPage, fetchNextPage]);

if (isError) {
return <Text>Something went wrong</Text>;
}
Expand All @@ -41,14 +57,15 @@ export function HotelsGridInfinite() {
return (
<>
<SimpleGrid cols={3}>
{data?.map(({ id, name, description, price }) => (
{data?.pages.flatMap(({data}) => data).map(({ id, name, description, price }) => (
<Hotel key={id} name={name} description={description} price={price} />
))}
</SimpleGrid>

<Button onClick={console.log} disabled={false}>
<div ref={ref} />
{/*<Button onClick={() => fetchNextPage()} disabled={!hasNextPage}>
Load more
</Button>
</Button>*/}
</>
);
}
28 changes: 23 additions & 5 deletions app/use-mutation/page.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,38 @@
"use client";
import * as React from "react";
import { Stack } from "@mantine/core";
import { useMutation } from "@tanstack/react-query";
import { AddHotelForm } from "@/app/components/AddHotelForm";
import {useMutation, useQueryClient} from "@tanstack/react-query";
import {AddHotelForm, HotelFormValues} from "@/app/components/AddHotelForm";
import { HotelsGrid } from "@/app/components/HotelsGrid";
import {delay} from "@/app/utils";

export default function Page() {
// @TODO: post a new hotel using useMutation
// POST http://localhost:8080/hotels
// Add optimistic update. Read more: https://tanstack.com/query/latest/docs/framework/react/guides/optimistic-updates

useMutation({});
const queryClient = useQueryClient();
const { mutate, isPending } = useMutation({
mutationKey: ["addHotel"],
mutationFn: async (values: HotelFormValues) => {
await delay();
await fetch('http://localhost:8080/hotels', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
});
},
onSettled: async () => {
return await queryClient.invalidateQueries({
queryKey: ['hotels'],
});
}
});

return (
<Stack>
<AddHotelForm onSubmit={(values) => console.log({ values })} />
<AddHotelForm onSubmit={(values) => mutate(values)} isSubmitting={isPending} />
<HotelsGrid />
</Stack>
);
Expand Down
44 changes: 7 additions & 37 deletions app/use-query/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,16 @@ import * as React from "react";
import { Center, Loader, SimpleGrid, Stack, Text } from "@mantine/core";
import { Hotel } from "@/app/components/Hotel";
import { HotelDTO } from "@/app/types";
import {useQuery} from "@tanstack/react-query";

const fetchHotels = async () => {
const res = await fetch("http://localhost:8080/hotels");
return await res.json();
};

export default function Page() {
// @TODO: Refactor this code to useQuery
// GET http://localhost:8080/hotels
const [isPending, setIsPending] = React.useState(true);
const [data, setData] = React.useState<HotelDTO[]>();
const [isError, setIsError] = React.useState();
const { data, isError, isPending } = useQuery({queryKey: ["hotels"], queryFn: fetchHotels});

React.useEffect(() => {
// Use `ignore` flag to avoid race conditions
let ignore = false;
setIsPending(true);
fetch(`http://localhost:8080/hotels`)
.then((res) => {
if (!res.ok) {
throw new Error("Failed to fetch");
}
return res.json();
})
.then((d) => {
if (!ignore) {
setData(d);
setIsError(undefined);
}
})
.catch((e) => {
if (!ignore) {
setIsError(e);
setData(undefined);
}
})
.finally(() => {
if (!ignore) {
setIsPending(false);
}
});
return () => {
ignore = true;
};
}, []);

if (isError) {
return <Text>Something went wrong</Text>;
Expand Down