Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jotai #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"jest": "^27.4.3",
"jest-resolve": "^27.4.2",
"jest-watch-typeahead": "^1.0.0",
"jotai": "^2.9.1",
"lodash": "^4.17.21",
"mini-css-extract-plugin": "^2.4.5",
"postcss": "^8.4.4",
Expand Down
29 changes: 15 additions & 14 deletions src/components/App/App.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import React from 'react';
import {
createBrowserRouter, RouterProvider,
} from "react-router-dom";
import {ListPage} from "../pages/ListPage/ListPage";
import {ItemPage} from "../pages/ItemPage/ItemPage";
import {LoaderProvider} from "../../hooks/useLoader";
import {Loader} from "../common/Loader/Loader";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { ListPage } from "../pages/ListPage/ListPage";
import { ItemPage } from "../pages/ItemPage/ItemPage";
import { LoaderProvider } from "../../hooks/useLoader";
import { Loader } from "../common/Loader/Loader";
import { Provider } from "jotai";

const router = createBrowserRouter([
{
Expand All @@ -14,16 +12,19 @@ const router = createBrowserRouter([
},
{
path: "/item/:id",
Component: ItemPage
}
Component: ItemPage,
},
]);

function App() {
return (
<LoaderProvider>
<RouterProvider router={router}/>
<Loader/> {/* Логичней в LoaderProvider вынести - но для тестирования глобального стейта тут ;) */}
</LoaderProvider>
<Provider>
<LoaderProvider>
<RouterProvider router={router} />
<Loader />
{/* Логичней в LoaderProvider вынести - но для тестирования глобального стейта тут ;) */}
</LoaderProvider>
</Provider>
);
}

Expand Down
102 changes: 45 additions & 57 deletions src/components/pages/ItemPage/ItemPage.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,41 @@
import {FC, useCallback, useEffect, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import {Item} from "../../../types/Item";
import {api} from "../../../api";
import {Button, Container, Form} from "react-bootstrap";
import {useLoader} from "../../../hooks/useLoader";
import {ConfirmModal} from "../../common/ConfirmModal/ConfirmModal";
import { FC, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Item } from "../../../types/Item";
import { Button, Container, Form } from "react-bootstrap";
import { ConfirmModal } from "../../common/ConfirmModal/ConfirmModal";
import { useAtom } from "jotai";
import { todoListState } from "../../../jotaiState";

export const ItemPage: FC = () => {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();

const loader = useLoader();
const [items, setItems] = useAtom(todoListState);

// Не использовать локальный стейт для демонстрации
const [item, setItem] = useState<Item | null>(null);
const [error, setError] = useState<string | null>(null);
const [removeConfirmationOpened, setRemoveConfirmationOpened] = useState(false);
const removeItem = (id: number) => {
setItems((items) => items.filter((item) => item.id !== id));
};

const fetch = useCallback(() => {
const hideLoader = loader.show();
// Специально не передал пропсом
// В демо тоже должен лежать отдельно в стейте (не в стейте списка для главной страницы)
// что бы проверить инвалидацию при переходе между страницами
api.getItem(Number(id))
.then((response) => {
if ('error' in response) {
setError(response.error);
return;
}
const item = items.find((item) => item.id === Number(id));
const error = !item ? "Item not found" : null;

setItem(response);
})
.finally(hideLoader);
}, []);
const setItem = (changedItem: Item) => {
const updatedList = items.map((item) => {
if (item.id === changedItem.id) {
return changedItem;
}
return item;
});

useEffect(() => {
fetch();
}, []);
setItems(updatedList);
};

const [removeConfirmationOpened, setRemoveConfirmationOpened] =
useState(false);

function renderContent() {
if (error) {
return (
<div style={{ color: 'red' }}>{error}</div>
)
return <div style={{ color: "red" }}>{error}</div>;
}

if (!item) {
Expand Down Expand Up @@ -71,46 +64,41 @@ export const ItemPage: FC = () => {
}

return (
<Container className='mt-3'>
<h1 className='mb-4'>Item</h1>
<Container className="mt-3">
<h1 className="mb-4">Item</h1>
{renderContent()}
<div>
<Button
className='m-1'
onClick={() => {
if (!item) return;
const hideLoader = loader.show();
api.updateItem(item)
.then(fetch)
.finally(hideLoader);
}}
>Save</Button>
<Button
className='m-1'
variant='danger'
className="m-1"
variant="danger"
onClick={() => setRemoveConfirmationOpened(true)}
>Remove</Button>
<Button className='m-1' href='/' variant='secondary'>Back</Button>
>
Remove
</Button>
<Button className="m-1" href="/" variant="secondary">
Back
</Button>
</div>
<h3 className='mt-5'>Cache invalidation</h3>
<h3 className="mt-5">Cache invalidation</h3>
<p>Please check scenario:</p>
<ul>
<li>Go to the <a href='/'>List page</a></li>
<li>
Go to the <a href="/">List page</a>
</li>
<li>Change this item in the list</li>
<li>Come back here and check that data will update</li>
</ul>
<ConfirmModal
show={removeConfirmationOpened}
title='Remove item'
title="Remove item"
onApply={() => {
if (!item) return;
const hideLoader = loader.show();
api.removeItem(item.id)
.then(() => navigate('/'))
.finally(hideLoader);

removeItem(item.id);
navigate("/");
}}
onCancel={() => setRemoveConfirmationOpened(false)}
/>
</Container>
)
);
};
90 changes: 39 additions & 51 deletions src/components/pages/ListPage/ListPage.tsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,68 @@
import {FC, useCallback, useEffect, useMemo, useState} from "react";
import {Button, Container, Form} from "react-bootstrap";
import {api} from "../../../api";
import {Item, Item as ItemType} from '../../../types/Item';
import './ListPage.css';
import {useLoader} from "../../../hooks/useLoader";
import {ConfirmModal} from "../../common/ConfirmModal/ConfirmModal";
import { FC, useState } from "react";
import { Button, Container, Form } from "react-bootstrap";
import { Item, Item as ItemType } from "../../../types/Item";
import "./ListPage.css";
import { useLoader } from "../../../hooks/useLoader";
import { ConfirmModal } from "../../common/ConfirmModal/ConfirmModal";
import { useAtom, useAtomValue } from "jotai";
import {
filteredTodoListState,
todoListOnlyCheckedState,
todoListState,
} from "../../../jotaiState";

export const ListPage: FC = () => {
const loader = useLoader();

// Не использовать локальный стейт для демонстрации
const [items, setItems] = useState<ItemType[]>([]);
const [onlyChecked, setOnlyChecked] = useState(false);
const [items, setItems] = useAtom(todoListState);
const [onlyChecked, setOnlyChecked] = useAtom(todoListOnlyCheckedState);
const [removingItem, setRemovingItem] = useState<ItemType | null>(null);

// Для демонстрации аля селекторов добавил фильтрацию
const filteredItems = useMemo(() => {
if (!onlyChecked) return items;
return items.filter((item) => item.checked);
}, [items, onlyChecked]);

const fetch = useCallback(() => {
const hideLoader = loader.show();
api.getItemList()
.then((items) => setItems(items))
.finally(hideLoader);
}, []);

useEffect(() => {
fetch();
}, []);
const filteredItems = useAtomValue(filteredTodoListState);

function renderItem(item: Item) {
return (
<div className='ListPage__item mb-2' key={item.id}>
<div className="ListPage__item mb-2" key={item.id}>
<Form.Check
className='m-2'
className="m-2"
checked={item.checked}
onChange={() => {
if (!item.id) return;
const newItem = {...item, checked: !item.checked};
setItems(items.map((item) => item.id === newItem.id ? newItem : item));
const newItem = { ...item, checked: !item.checked };
setItems(
items.map((item) => (item.id === newItem.id ? newItem : item))
);
}}
/>
<div className='ListPage__link'><a href={`item/${item.id}`}>{item.text}</a></div>
<div className="ListPage__link">
<a href={`item/${item.id}`}>{item.text}</a>
</div>
{item.id === 0 ? null : (
<Button
variant="outline-secondary"
size='sm'
size="sm"
onClick={() => setRemovingItem(item)}
>X</Button>
>
X
</Button>
)}
</div>
);
}

return (
<Container className='mt-3' style={{ width: 800 }}>
<h1 className='mb-4'>Items list</h1>
<Container className="mt-3" style={{ width: 800 }}>
<h1 className="mb-4">Items list</h1>
<Form.Check
type="switch"
label="Only checked (for selectors)"
checked={onlyChecked}
onChange={() => setOnlyChecked(!onlyChecked)}
/>
<div className='mt-4 mb-4'>
<div className="mt-4 mb-4">
{renderItem({
id: 0,
text: 'Not exists item (for error testing)',
text: "Not exists item (for error testing)",
checked: true,
})}
{filteredItems.map(renderItem)}
Expand All @@ -77,22 +72,15 @@ export const ListPage: FC = () => {
onClick={() => {
const newItem = {
id: +new Date(),
text: 'New item',
checked: false
text: "New item",
checked: false,
};
setItems([...items, newItem]);
api.addItem(newItem);
}}
>Add item</Button>
<Button
onClick={() => {
const hideLoader = loader.show();
api.updateItemList(items)
.then(fetch)
.finally(hideLoader);
}}
>Save</Button>
<h3 className='mt-5'>Cache invalidation</h3>
>
Add item
</Button>
<h3 className="mt-5">Cache invalidation</h3>
<p>Please check scenario:</p>
<ul>
<li>Go to any item page</li>
Expand All @@ -101,7 +89,7 @@ export const ListPage: FC = () => {
</ul>
<ConfirmModal
show={!!removingItem}
title='Remove item'
title="Remove item"
onApply={() => {
if (!removingItem) return;
setItems(items.filter(({ id }) => id !== removingItem.id));
Expand Down
13 changes: 13 additions & 0 deletions src/jotaiState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { Item } from "./types/Item";

export const todoListState = atomWithStorage<Item[]>("items", []);

export const todoListOnlyCheckedState = atom<boolean>(false);

export const filteredTodoListState = atom<Item[]>((get) => {
const onlyChecked = get(todoListOnlyCheckedState);
const list = get(todoListState);
return onlyChecked ? list.filter((item) => item.checked) : list;
});