Giter Site home page Giter Site logo

Comments (2)

coolsoftwaretyler avatar coolsoftwaretyler commented on June 6, 2024

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:

  1. The ViewModel, which models the state of your application, but does not need to have full parity with your server state or database modeling
  2. 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:

  1. 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.
  2. Define a NoteSnapshot interface based on the snapshot types of the Note model.
  3. Then define a utility type from that interface, which Omits the id, because we don't know it on the client yet.
  4. 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.
  5. 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.
  6. 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.
  7. Optional: I threw a rudimentary error if data was missing, but this is a place you could do more interesting error handling
  8. The 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.
  9. We wire up the server to expect the return type of FormViewModel's formData view and return an id
  10. After we successfully get an id, we tell the viewModel to create its note.
  11. 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.

coolsoftwaretyler avatar coolsoftwaretyler commented on June 6, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.