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

Play with mobx #1

Open
wants to merge 10 commits into
base: completed-tutorial
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 43 additions & 0 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"express": "^4.18.1",
"helmet": "^6.0.0",
"heroku-ssl-redirect": "^0.1.1",
"mobx": "^6.6.2",
"mobx-react-lite": "^3.4.0",
"pg": "^8.8.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
113 changes: 61 additions & 52 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,87 +1,96 @@
import { useEffect, useState } from "react";
import React, { useEffect, useState } from "react";
import { remult } from "remult";
import { Task } from "./shared/Task";
import { TasksController } from "./shared/TasksController";
import { observer } from "mobx-react-lite";
import { action, makeAutoObservable, observable, runInAction } from 'mobx';

const taskRepo = remult.repo(Task);

async function fetchTasks(hideCompleted: boolean) {
return taskRepo.find({
limit: 20,
orderBy: { completed: "asc" },
where: { completed: hideCompleted ? false : undefined }
});
}


class Store {
taskRepo = remult.repo(Task);
readonly tasks = observable<Task>([]);
hideCompleted = false;
constructor() {
makeAutoObservable(this);
}
replaceTasks(t: Task[]) {
this.tasks.replace(t.map(t => makeAutoObservable({ ...t })));
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
}
async loadTasks() {
this.replaceTasks(await
this.taskRepo.find({
limit: 20,
orderBy: { completed: "asc" },
where: { completed: this.hideCompleted ? false : undefined }
}));
}
addTask() {
this.tasks.push(makeAutoObservable(new Task()))
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
}
async saveTask(task: Task) {
try {
const savedTask = await this.taskRepo.save(task);
runInAction(() => store.tasks[store.tasks.indexOf(task)] = savedTask);
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
} catch (error: any) {
alert(error.message);
}
}
async deleteTask(task: Task) {
await this.taskRepo.delete(task);
runInAction(() => store.tasks.remove(task));
}
async setAll(completed: boolean) {
await TasksController.setAll(completed);
this.loadTasks();
}
}
const store = new Store();

function App() {

Choose a reason for hiding this comment

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

  1. I'd separate the store from the app.
  2. Store should only be instantiated in app and not in store file.

const [tasks, setTasks] = useState<Task[]>([]);
const [hideCompleted, setHideCompleted] = useState(false);
return <Todo store={store} />

}
const Todo: React.FC<{ store: Store }> = observer(({ store }) => {
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
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]);
Comment on lines 9 to +11

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 DOMContentLoaded event 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. :(

Copy link
Contributor Author

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?

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-react bindings. The mobx-react package supports legacy (class based) components + mobx-react-lite, which supports only function components. I'd install only the latter and wrap each component in observer.

Copy link
Contributor Author

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 reaction
https://mobx.js.org/reactions.html

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 observer and you're done.

Copy link
Contributor Author

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())?

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's observer wrapper for the components which should be reactive.

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 => {
const prev = task.completed;
task.completed = e.target.checked;
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
})} />
<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 onClick={() => store.saveTask(task)}>Save</button>
<button onClick={() => store.deleteTask(task)}>Delete</button>
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
</div>
);
})}

</main>
<button onClick={addTask}>Add Task</button>
<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 onClick={() => store.setAll(true)}>Set all as completed</button>
<button onClick={() => store.setAll(false)}>Set all as uncompleted</button>
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
noam-honig marked this conversation as resolved.
Show resolved Hide resolved
</div>

</div>
);
}
});


export default App;