Comments (2)
Hey @exinferis - thanks for filing this issue. I agree this can be a little fiddly with MST. At a high level, I think you can smooth things over by thinking about two distinct models in your MST codebase:
- The ViewModel, which models the state of your application, but does not need to have full parity with your server state or database modeling
- Individual models that do duplicate your server-side modeling, but can be passed around and handled by the ViewModel.
These two things can interact with one another, and you can model this whole flow through the ViewModel itself, but also handle actual server alongside.
Here's how I would do this in my own app:
import { types, getSnapshot, SnapshotOut, SnapshotIn } from "mobx-state-tree";
const Note = types.model("Note", {
id: types.identifierNumber,
title: types.string,
message: types.string,
date: types.string,
});
interface NoteSnapshot extends SnapshotIn<typeof Note> {}
type FormData = Omit<NoteSnapshot, "id">;
const FormViewModel = types
.model("FormViewModel", {
note: types.maybe(Note),
title: types.maybe(types.string),
message: types.maybe(types.string),
date: types.maybe(types.string),
})
.views((self) => ({
get formData(): FormData {
const { title, message, date } = self;
if (!title || !message || !date) {
throw new Error("Missing required fields");
}
return { title, message, date };
},
}))
.actions((self) => ({
createNote(id: number) {
const { formData } = self;
const note = Note.create({
...formData,
id,
});
self.note = note;
},
}));
let counter = 0;
async function server(snapshot: FormData): Promise<number> {
console.log("Received input", snapshot);
// Return an auto-incrementing integer as ID
counter += 1;
return counter;
}
(async () => {
// Instantiate the view model of your form. In practice, this would be part of a UI or other process
const noteForm = FormViewModel.create({
title: "Hello from MST",
message: "Hopefully this helps",
date: "2024-02-15",
});
// Send to the server and get an id
const id = await server(noteForm.formData);
noteForm.createNote(id);
const finalSnapshot = getSnapshot(noteForm);
console.log(JSON.stringify(finalSnapshot, null, 2));
})();
You can work with this code, fork it, etc. in CodeSandbox.
Here's my thought process in designing this:
- Design a
Note
model, which mirrors the server/database schema (as an aside, we do have a date primitive if you need one, but I also sometimes just use ISO 8601 strings for dates as well. - Define a
NoteSnapshot
interface based on the snapshot types of theNote
model. - Then define a utility type from that interface, which Omits the
id
, because we don't know it on the client yet. - Then, define a separate model type. I made an assumption that you've got users filling out some kind of form for notes. You don't have to map this to a UI like a form. You could do this in-memory, in some background process in your app as well. For now, let's stick with the form idea here.
FormViewModel
knows about four things. It knows about the theNote
model type, and it has one (you could do an array, a map, something else if you need to hold many). It also knows about the title, message, and date. Notice I typed these withmaybe
- so you could use this as a controlled input with some kind of HTML form where the value might beundefined
.- Since the view models data could be undefined, but the server model has no optionality in its title/message/date field, we also have a
formData
view, which is where we can do some client-side validation of the inputs if need be. You could even transform things here - this is great for when you have something like, a form that wants users to input dollars, but your server takes data as integers of cents. - Optional: I threw a rudimentary error if data was missing, but this is a place you could do more interesting error handling
- The
FormViewModel
also knows how to instantiate its childNote
instance: all it needs is the id (which it gets elsewhere, i.e. the server), and then it grabs its own currentformData
and sets the combination as its ownnote
child. - We wire up the server to expect the return type of
FormViewModel
'sformData
view and return anid
- After we successfully get an
id
, we tell the viewModel to create itsnote
. - To demonstrate the result, I've logged out the final snapshot of the ViewModel.
Let me know if that resolves your issue or not. Happy to talk further, but this is how I'd approach it. I'm sorry we don't have a ton of best practice guides for stuff like this.
from mobx-state-tree.
Hey @exinferis - since I haven't heard back from you in a while, I'm going to convert this issue to a discussion and mark my answer as the correct one. That will close out the issue, and make it easier for folks to find this as an example if they need something similar. And of course, if my answer was insufficient, you can let me know and we can iterate in the discussions. Thanks!
from mobx-state-tree.
Related Issues (20)
- RootStore type becomes "any" the moment we call a RootStore model action using yield on a child model action HOT 3
- Unintended behavior when creating new models with falsy first argument HOT 8
- detach can corrupt the identifierCache HOT 2
- Add tests and documentation for debug names in complex types
- Add tests and documentation for new parent argument to `types.optional` HOT 1
- Document how MST lazily creates objects HOT 1
- Use getTime() to check for Date equality HOT 8
- Remove Lerna config and lift MST sub-package up
- When observe() a MST node's primitive property, TypeScript get the wrong type of oldValue & newValue HOT 1
- Add safeMap utility (or something like it)
- Broken Map type in 5.3.0 HOT 8
- TypeError: 0, _mobx.defineProperty is not a function (it is undefined) HOT 4
- applySnapshot is slow HOT 1
- Unexpected error "Сannot finalize the creation of a node that is already dead" while applying snapshot HOT 16
- Linters do not recognize `fail` as a required import in library code HOT 4
- Better documentation on action/view definitions and their impact on IDE introspection, navigation and refactoring HOT 2
- Missing docs for `types.lazy` HOT 2
- getMembers does not work as expected, behaviour change between 5.1.0 and 5.4.1 HOT 11
- Model constructor modifies descriptor object HOT 5
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mobx-state-tree.