Closed exinferis closed 4 months ago
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:
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:
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.NoteSnapshot
interface based on the snapshot types of the Note
model.id
, because we don't know it on the client yet.FormViewModel
knows about four things. It knows about the the Note
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 with maybe
- so you could use this as a controlled input with some kind of HTML form where the value might be undefined
.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.FormViewModel
also knows how to instantiate its child Note
instance: all it needs is the id (which it gets elsewhere, i.e. the server), and then it grabs its own current formData
and sets the combination as its own note
child.FormViewModel
's formData
view and return an id
id
, we tell the viewModel to create its note
.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.
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!
Bug report
Describe the expected behavior
I have a standard REST pattern for my application, meaning that data is created on the client side, sent via POST request to the server, then stored and sent back by the server with the generated id.
So my NOTES for example
{ title: string, message: string, date: string }
obviously become{ id: number, title: string, message: string, date: string }
after creation. This is fairly standard for every web application I know. It seems to be nearly impossible to achieve in MST when using identifier oder identifierNumber though, since those are not optional and immutable which renders it impossible to use this standard pattern. All other issues regarding this behavior were inconclusive or closed. What is the approach in MST to use a standard REST interface when creating new data sets?