-
Notifications
You must be signed in to change notification settings - Fork 9
Play with mobx #1
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
Open
noam-honig
wants to merge
10
commits into
completed-tutorial
Choose a base branch
from
play-with-mobx
base: completed-tutorial
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
10 commits
Select commit
Hold shift + click to select a range
fb62104
test play with mobx
noam-honig 635c7d7
installed mobx
noam-honig e40af95
Update src/App.tsx
noam-honig 24e8ca4
implemented nick's comments
noam-honig f580fec
Merge branch 'play-with-mobx' of https://github.com/remult/react-vite…
noam-honig a988cbd
tasks cleanup
noam-honig f703f30
refactored store to a separate file
noam-honig b9a3793
removed unnecessary spaces
noam-honig 331497a
adjusted spaces
noam-honig 62e5980
updated indent to highlight differences
noam-honig 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 hidden or 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 hidden or 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,87 +1,43 @@ | ||
| import { useEffect, useState } from "react"; | ||
| import { remult } from "remult"; | ||
| import { Task } from "./shared/Task"; | ||
| import { TasksController } from "./shared/TasksController"; | ||
| import { useEffect } from "react"; | ||
| import { observer } from "mobx-react-lite"; | ||
| import { action } from 'mobx'; | ||
| import { Store } from "./Store"; | ||
|
|
||
| const taskRepo = remult.repo(Task); | ||
|
|
||
| async function fetchTasks(hideCompleted: boolean) { | ||
| return taskRepo.find({ | ||
| limit: 20, | ||
| orderBy: { completed: "asc" }, | ||
| where: { completed: hideCompleted ? false : undefined } | ||
| }); | ||
| } | ||
|
|
||
|
|
||
|
|
||
| function App() { | ||
| const [tasks, setTasks] = useState<Task[]>([]); | ||
| const [hideCompleted, setHideCompleted] = useState(false); | ||
| export const store = new Store(); | ||
|
|
||
| const App = observer(() => { | ||
| useEffect(() => { | ||
| fetchTasks(hideCompleted).then(setTasks); | ||
| }, [hideCompleted]); | ||
|
|
||
| const addTask = () => { | ||
| setTasks([...tasks, new Task()]) | ||
| }; | ||
| const setAll = async (completed: boolean) => { | ||
| await TasksController.setAll(completed); | ||
| setTasks(await fetchTasks(hideCompleted)); | ||
| } | ||
|
|
||
| store.loadTasks() | ||
| }, [store.hideCompleted]); | ||
| return ( | ||
| <div> | ||
| <input | ||
| type="checkbox" | ||
| checked={hideCompleted} | ||
| onChange={e => setHideCompleted(e.target.checked)} /> Hide Completed | ||
| checked={store.hideCompleted} | ||
| onChange={action(e => store.hideCompleted = e.target.checked)} /> Hide Completed | ||
noam-honig marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| <main> | ||
noam-honig marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| {tasks.map(task => { | ||
| const handleChange = (values: Partial<Task>) => { | ||
| setTasks(tasks.map(t => t === task ? { ...task, ...values } : t)); | ||
| }; | ||
|
|
||
| const saveTask = async () => { | ||
| try { | ||
| const savedTask = await taskRepo.save(task); | ||
| setTasks(tasks.map(t => t === task ? savedTask : t)); | ||
| } catch (error: any) { | ||
| alert(error.message); | ||
| } | ||
| } | ||
|
|
||
|
|
||
| const deleteTask = async () => { | ||
| await taskRepo.delete(task); | ||
| setTasks(tasks.filter(t => t !== task)); | ||
| }; | ||
|
|
||
| {store.tasks.map(task => { | ||
| return ( | ||
| <div key={task.id}> | ||
noam-honig marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| <input type="checkbox" | ||
| checked={task.completed} | ||
| onChange={e => handleChange({ completed: e.target.checked })} /> | ||
| onChange={action(e => task.completed = e.target.checked)} /> | ||
| <input | ||
| value={task.title} | ||
| onChange={e => handleChange({ title: e.target.value })} /> | ||
| <button onClick={saveTask}>Save</button> | ||
| <button onClick={deleteTask}>Delete</button> | ||
| onChange={action(e => task.title = e.target.value)} /> | ||
noam-honig marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| <button type="button" onClick={() => store.saveTask(task)}>Save</button> | ||
| <button type="button" onClick={() => store.deleteTask(task)}>Delete</button> | ||
| </div> | ||
| ); | ||
| })} | ||
|
|
||
| </main> | ||
| <button onClick={addTask}>Add Task</button> | ||
| <button type="button" onClick={() => store.addTask()}>Add Task</button> | ||
| <div> | ||
| <button onClick={() => setAll(true)}>Set all as completed</button> | ||
| <button onClick={() => setAll(false)}>Set all as uncompleted</button> | ||
| <button type="button" onClick={() => store.setAll(true)}>Set all as completed</button> | ||
| <button type="button" onClick={() => store.setAll(false)}>Set all as uncompleted</button> | ||
| </div> | ||
|
|
||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| }); | ||
|
|
||
| export default App; | ||
This file contains hidden or 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,43 @@ | ||
| import { remult } from "remult"; | ||
| import { Task } from "./shared/Task"; | ||
| import { TasksController } from "./shared/TasksController"; | ||
| import { makeAutoObservable, runInAction } from 'mobx'; | ||
| import { store } from "./App"; | ||
|
|
||
| export class Store { | ||
| taskRepo = remult.repo(Task); | ||
| tasks: Task[] = []; | ||
| hideCompleted = false; | ||
| constructor() { | ||
| makeAutoObservable(this); | ||
| } | ||
| replaceTasks(tasks: Task[]) { | ||
| this.tasks = tasks; | ||
| } | ||
| async loadTasks() { | ||
| this.replaceTasks(await this.taskRepo.find({ | ||
| limit: 20, | ||
| orderBy: { completed: "asc" }, | ||
| where: { completed: this.hideCompleted ? false : undefined } | ||
| })); | ||
| } | ||
| addTask() { | ||
| this.tasks.push(new Task()); | ||
| } | ||
| async saveTask(task: Task) { | ||
| try { | ||
| const savedTask = await this.taskRepo.save(task); | ||
| runInAction(() => store.tasks[store.tasks.indexOf(task)] = savedTask); | ||
| } catch (error: any) { | ||
| alert(error.message); | ||
| } | ||
| } | ||
| async deleteTask(task: Task) { | ||
| await this.taskRepo.delete(task); | ||
| runInAction(() => this.tasks = this.tasks.filter(t => t !== task)); | ||
| } | ||
| async setAll(completed: boolean) { | ||
| await TasksController.setAll(completed); | ||
| this.loadTasks(); | ||
| } | ||
| } |
This file contains hidden or 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
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.
I'd tie this to the DOM's
DOMContentLoadedevent like this:document.addEventListener('DOMContentLoaded', store.loadTasks, { once: true })instead of React.But I'm also painfully aware that that's not how most people write react apps nowadays. :(
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.
By using the use effect - I also get the automatic reload on change of hideCompleted - one way is to make the change through a mutation - I get that, but what's the "mobx" way of triggering an action on change of one or more state members?
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.
The mobx way of adding reactivity to react is via
mobx-reactbindings. Themobx-reactpackage supports legacy (class based) components +mobx-react-lite, which supports only function components. I'd install only the latter and wrap each component inobserver.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.
I think that a possible answer to my question (of reloading based on change of hideCompleted) is to use mobx
reactionhttps://mobx.js.org/reactions.html
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.
Yeah, you can do that and in fact that's what the mobx-react bindings use. But why would you bother with a lower level and verbose API when you already have a solution: just wrap in
observerand you're done.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.
Just to make sure that I get you correctly.
Relace the code for loadTasks()
to be:
observer(()=>loadTasksImplementation())?
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.
No. I'd do the initial load via a DOM event, decoupled from the UI rendering, like in the first message in this thread. This takes care of the bootstrapping phase of the app - it happens once and that's it.
Any other re-rendering as a result of changes to anything that mobx manages is taken care of using props, thanks so
mobx-react'sobserverwrapper for the components which should be reactive.