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

Add mobx models #8

Open
wants to merge 2 commits 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
66 changes: 63 additions & 3 deletions package-lock.json

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

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@babel/core": "^7.16.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
"@svgr/webpack": "^5.5.0",
"@tanstack/react-query": "^5.51.23",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
Expand Down Expand Up @@ -39,6 +40,8 @@
"jest-watch-typeahead": "^1.0.0",
"lodash": "^4.17.21",
"mini-css-extract-plugin": "^2.4.5",
"mobx": "^6.13.1",
"mobx-react-lite": "^4.0.7",
"postcss": "^8.4.4",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.2.1",
Expand Down
15 changes: 10 additions & 5 deletions src/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import {
} from "react-router-dom";
import {ListPage} from "../pages/ListPage/ListPage";
import {ItemPage} from "../pages/ItemPage/ItemPage";
import {LoaderProvider} from "../../hooks/useLoader";
import {LoaderProvider} from "../../hooks/useLoaderModel/useLoaderModel";
import {Loader} from "../common/Loader/Loader";
import {QueryClient, QueryClientProvider} from "@tanstack/react-query";

const router = createBrowserRouter([
{
Expand All @@ -18,12 +19,16 @@ const router = createBrowserRouter([
}
]);

const client = new QueryClient();

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

Expand Down
9 changes: 5 additions & 4 deletions src/components/common/Loader/Loader.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {FC} from "react";
import {Spinner} from "react-bootstrap";
import './Loader.css';
import {useLoader} from "../../../hooks/useLoader";
import {useLoaderModel} from "../../../hooks/useLoaderModel";
import {observer} from "mobx-react-lite";

export const Loader: FC = () => {
const loader = useLoader();
export const Loader: FC = observer(() => {
const loader = useLoaderModel();

if (!loader.isLoading) {
return null;
Expand All @@ -17,4 +18,4 @@ export const Loader: FC = () => {
</Spinner>
</div>
)
}
})
94 changes: 31 additions & 63 deletions src/components/pages/ItemPage/ItemPage.tsx
Original file line number Diff line number Diff line change
@@ -1,94 +1,63 @@
import {FC, useCallback, useEffect, useState} from "react";
import {useNavigate, useParams} from "react-router-dom";
import {Item} from "../../../types/Item";
import {FC} from "react";
import {useNavigate} from "react-router-dom";
import {api} from "../../../api";
import {Button, Container, Form} from "react-bootstrap";
import {useLoader} from "../../../hooks/useLoader";
import {useLoaderModel} from "../../../hooks/useLoaderModel";
import {ConfirmModal} from "../../common/ConfirmModal/ConfirmModal";
import {observer} from "mobx-react-lite";
import {useItemModel} from "./hooks/useItemModel";

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

const loader = useLoader();

// Не использовать локальный стейт для демонстрации
const [item, setItem] = useState<Item | null>(null);
const [error, setError] = useState<string | null>(null);
const [removeConfirmationOpened, setRemoveConfirmationOpened] = useState(false);
export const ItemPage: FC = observer(() => {
const { model: itemModel, error, refetch } = useItemModel();

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

setItem(response);
})
.finally(hideLoader);
}, []);
const navigate = useNavigate();

useEffect(() => {
fetch();
}, []);
const loader = useLoaderModel();

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

if (!item) {
return null;
}
if (!itemModel) {
return null;
}

return (
return (
<Container className='mt-3'>
<h1 className='mb-4'>Item</h1>
<Form>
<Form.Group className="mb-3">
<Form.Check
type="checkbox"
label="Checked"
checked={item.checked}
onChange={() => setItem({ ...item, checked: !item.checked })}
checked={itemModel.checked}
onChange={() => itemModel.toggle()}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Text</Form.Label>
<Form.Control
value={item.text}
onChange={(e) => setItem({ ...item, text: e.target.value })}
value={itemModel.text}
onChange={(e) => itemModel.text = e.target.value}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не будет работать корректно, потому что вызвано вне экшна. Надо или сделать экшн и вызвать его так itemModel.setText(e.target.value), или обернуть код из onChange в runInAction.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Разобрались, что работает из-за того, что text имеет сеттер

/>
</Form.Group>
</Form>
);
}

return (
<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)
api.updateItem(itemModel.toJs())
.then(refetch)
.finally(hideLoader);
}}
>Save</Button>
<Button
className='m-1'
variant='danger'
onClick={() => setRemoveConfirmationOpened(true)}
onClick={() => itemModel.isRemoving = true}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут тоже надо менять состояние стора через экшн.

>Remove</Button>
<Button className='m-1' href='/' variant='secondary'>Back</Button>
</div>
Expand All @@ -100,17 +69,16 @@ export const ItemPage: FC = () => {
<li>Come back here and check that data will update</li>
</ul>
<ConfirmModal
show={removeConfirmationOpened}
show={itemModel.isRemoving}
title='Remove item'
onApply={() => {
if (!item) return;
const hideLoader = loader.show();
api.removeItem(item.id)
api.removeItem(itemModel.id)
.then(() => navigate('/'))
.finally(hideLoader);
}}
onCancel={() => setRemoveConfirmationOpened(false)}
onCancel={() => itemModel.isRemoving = false}
/>
</Container>
)
};
});
56 changes: 56 additions & 0 deletions src/components/pages/ItemPage/hooks/useItemModel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import {useParams} from "react-router-dom";
import {useLoaderModel} from "../../../../hooks/useLoaderModel";
import {useQuery} from "@tanstack/react-query";
import {api} from "../../../../api";
import {useEffect, useState} from "react";
import {ItemModel} from "../../../../models/ItemModel";
import {Item} from "../../../../types/Item";

type Result = {
model: ItemModel | null,
error: string | null,
refetch(): void,
}

type ItemResponseError = {error: string};

function isErrorItem(data: Item | ItemResponseError | undefined): data is ItemResponseError {
return Boolean(data && 'error' in data);
}

export const useItemModel = (): Result => {
const { id } = useParams<{ id: string }>();
const loader = useLoaderModel();

const {data, refetch, isFetching, isError: isItemError} = useQuery({
queryKey: ['item', id],
queryFn: () => api.getItem(Number(id)),
});

useEffect(() => {
if (isFetching) {
return loader.show();
}
}, [isFetching, loader]);

const [model, setModel] = useState<ItemModel | null>(null);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
if(isItemError || isErrorItem(data)) {
setError((data as ItemResponseError)?.error || 'Item data loading error');
return
}

if (data) {
if (model) {
model.update(data);
return;
}

setModel(new ItemModel({ item: data }))
}
},[data, isItemError, model, isFetching]);

return { model, error, refetch };
}
Loading