-
Notifications
You must be signed in to change notification settings - Fork 2
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
EgorKluch
wants to merge
2
commits into
main
Choose a base branch
from
mobx
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} | ||
/> | ||
</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} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут тоже надо менять состояние стора через экшн. |
||
>Remove</Button> | ||
<Button className='m-1' href='/' variant='secondary'>Back</Button> | ||
</div> | ||
|
@@ -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> | ||
) | ||
}; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Разобрались, что работает из-за того, что
text
имеет сеттер