Skip to content

Commit

Permalink
react query
Browse files Browse the repository at this point in the history
  • Loading branch information
rosendolu committed Oct 30, 2024
1 parent 4678467 commit c84bb9f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 1e3 * 60 * 5,
},
},
});
Expand Down
43 changes: 41 additions & 2 deletions src/pages/react-query.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,56 @@
import { useQuery } from '@tanstack/react-query';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { Alert, Button, Space, Tag, Typography } from 'antd';
import classNames from 'classnames';
import React from 'react';
import { Facebook } from 'react-content-loader';
import ReactJson from 'react-json-view';

export default function ReactQuery() {
return (
<div>
<Typography.Title level={2}>React Query In Action</Typography.Title>
<PaginatedQuery></PaginatedQuery>
<User></User>
</div>
);
}

function PaginatedQuery() {
const [page, setPage] = React.useState(0);

const fetchProjects = (page = 0) =>
fetch(`https://randomuser.me/api?q=${page}`)
.then(res => res.json())
.then(res => ((res.hasMore = true), res));

const { isPending, isLoading, isRefetching, isError, error, data, isFetching, isPlaceholderData } = useQuery({
queryKey: ['projects', page],
queryFn: () => fetchProjects(page),
placeholderData: keepPreviousData,
});

return (
<div>
{isPending ? <div>Loading...</div> : isError ? <div>Error: {error.message}</div> : <div>data</div>}
<span>Current Page: {page + 1}</span> <br />
<Button onClick={() => setPage(old => Math.max(old - 1, 0))} disabled={page === 0}>
Previous Page
</Button>
<Button
onClick={() => {
if (!isPlaceholderData && data.hasMore) {
setPage(old => old + 1);
}
}}
// Disable the Next Page button until we know a next page is available
disabled={isPlaceholderData || !data?.hasMore}>
Next Page
</Button>
{isFetching ? <span> Loading...</span> : null}
</div>
);
}

function User() {
const user = useQuery({
queryKey: ['user'],
Expand All @@ -24,6 +62,7 @@ function User() {
},
});
console.log('user', user);

if (user.isLoading) {
return <Facebook></Facebook>;
}
Expand All @@ -44,7 +83,7 @@ function User() {
)}
</Space>
<div className={classNames('text-left', user.isFetching ? 'opacity-50' : '')}>
{user.isError && <Alert type="error" message={user.error?.toString()}></Alert>}
{user.isError && <Alert closable type="error" message={user.error?.toString()}></Alert>}
<ReactJson name={false} displayObjectSize={false} displayDataTypes={false} src={user.data}></ReactJson>
</div>
</>
Expand Down

0 comments on commit c84bb9f

Please sign in to comment.