### Install Dependencies for MobX-State-Tree React App
Source: https://mobx-state-tree.js.org/intro/getting-started
Installs necessary dependencies for a React project using MobX and MobX-State-Tree. Requires Node.js and npm/yarn. Installs `mobx`, `mobx-react-lite`, and `mobx-state-tree`.
```bash
npx create-react-app mst-todo
yarn add mobx mobx-react-lite mobx-state-tree
```
--------------------------------
### Creating RootStore with User Snapshots
Source: https://mobx-state-tree.js.org/intro/getting-started
This example shows how to correctly create a `RootStore` instance by providing snapshots that include the required `id` for each user. Missing identifiers would result in an error.
```javascript
const store = RootStore.create({
users: {
1: {
id: "1",
name: "mweststrate"
},
2: {
id: "2",
name: "mattiamanzati"
},
3: {
id: "3",
name: "johndoe"
}
},
todos: {
1: {
name: "Eat a cake",
done: true
}
}
})
```
--------------------------------
### Connect MST Store to React Component using MobX
Source: https://mobx-state-tree.js.org/intro/getting-started
Integrates a MobX State Tree store with a React component using the observer HOC from mobx-react-lite. This allows the component to react to changes in the MST store. Ensure mobx-react-lite is installed as a dependency.
```javascript
import { observer } from "mobx-react-lite"
const App = observer((props) => (
))
```
--------------------------------
### Create MobX State Tree Instance with Initial Values
Source: https://mobx-state-tree.js.org/intro/getting-started
Shows how to create a MobX State Tree model instance (`Todo`) and provide initial values for its attributes directly within the `.create()` function. This allows for immediate customization of the instance's state upon creation. The example logs the snapshot to show the updated state.
```javascript
const eat = Todo.create({ name: "eat" })
console.log("Eat TODO:", getSnapshot(eat)) // => will print {name: "eat", done: false}
```
--------------------------------
### Create MST Store Instance with Initial Data (JavaScript)
Source: https://mobx-state-tree.js.org/intro/getting-started
Initializes a MobX State Tree store by creating an instance of the RootStore model with predefined users and todos. This demonstrates how to populate the store with initial data, setting up the state for the application.
```javascript
const store = RootStore.create({
users: {
1: {
name: "mweststrate"
},
2: {
name: "mattiamanzati"
},
3: {
name: "johndoe"
}
},
todos: {
1: {
name: "Eat a cake",
done: true
}
}
})
```
--------------------------------
### Create MobX State Tree Models and Instances
Source: https://mobx-state-tree.js.org/intro/getting-started
Defines `Todo` and `User` models using `types.model` and creates basic instances of these models. It then demonstrates how to retrieve the state snapshot of these instances using `getSnapshot`. This is the foundational step for state management with MobX State Tree.
```javascript
import { types, getSnapshot } from "mobx-state-tree"
const Todo = types.model({
name: "",
done: false
})
const User = types.model({
name: ""
})
const john = User.create()
const eat = Todo.create()
console.log("John:", getSnapshot(john))
console.log("Eat TODO:", getSnapshot(eat))
```
--------------------------------
### Get MST Store Snapshot in JavaScript
Source: https://mobx-state-tree.js.org/intro/getting-started
Uses the `getSnapshot` function from the MST package to generate a serializable snapshot of the current store's state. This is useful for debugging, persistence, and testing.
```javascript
console.log(getSnapshot(store))
/*
{
"users": {},
"todos": {
"1": {
"name": "Eat a cake",
"done": true
}
}
}
*/
```
--------------------------------
### Call MST Model Actions in JavaScript
Source: https://mobx-state-tree.js.org/intro/getting-started
Demonstrates how to call defined actions on MST model instances. `store.addTodo` creates a new todo, and `store.todos.get(1).toggle` modifies the `done` property of the todo with ID 1.
```javascript
store.addTodo(1, "Eat a cake")
store.todos.get(1).toggle()
```
--------------------------------
### React Components for Todo Management and User Selection with MobX
Source: https://mobx-state-tree.js.org/intro/getting-started
Provides React components using MobX's `observer` HOC for real-time updates. Includes `UserPickerView` for selecting a user, `TodoView` for displaying and editing a todo item, `TodoCounterView` for task counts, and `AppView` for the main application layout with task addition and display.
```javascript
const UserPickerView = observer((props) => (
))
const TodoView = observer((props) => (
))
```
--------------------------------
### Implement Time Travel with MST Snapshots in JavaScript
Source: https://mobx-state-tree.js.org/intro/getting-started
Provides a JavaScript implementation for time travel functionality using MST snapshots. It listens for snapshot changes with `onSnapshot`, stores them, and uses `applySnapshot` to revert to previous states.
```javascript
import { applySnapshot, onSnapshot } from "mobx-state-tree"
var states = []
var currentFrame = -1
onSnapshot(store, (snapshot) => {
if (currentFrame === states.length - 1) {
currentFrame++
states.push(snapshot)
}
})
export function previousState() {
if (currentFrame === 0) return
currentFrame--
applySnapshot(store, states[currentFrame])
}
export function nextState() {
if (currentFrame === states.length - 1) return
currentFrame++
applySnapshot(store, states[currentFrame])
}
```
--------------------------------
### Define Computed Properties in MobX State Tree
Source: https://mobx-state-tree.js.org/intro/getting-started
Adds computed properties ('views') to an MST model to derive state. These properties automatically recompute when their dependencies change, improving performance by avoiding unnecessary recalculations. This example defines `pendingCount` and `completedCount` for todos. Requires mobx-state-tree.
```javascript
const RootStore = types
.model({
users: types.map(User),
todos: types.map(Todo)
})
.views((self) => ({
get pendingCount() {
return Array.from(self.todos.values()).filter((todo) => !todo.done).length
},
get completedCount() {
return Array.from(self.todos.values()).filter((todo) => todo.done).length
}
}))
.actions((self) => ({
addTodo(id, name) {
self.todos.set(id, Todo.create({ name }))
}
}))
```
--------------------------------
### Define MobX State Tree Model with Actions for Reference Management
Source: https://mobx-state-tree.js.org/intro/getting-started
Defines a `Todo` model using MobX State Tree, including properties like `name`, `done`, and a `user` reference. It also includes actions `setName`, `setUser`, and `toggle` to modify the model's state, with `setUser` handling the assignment or unassignment of a user reference.
```javascript
const Todo = types
.model({
name: types.optional(types.string, ""),
done: types.optional(types.boolean, false),
user: types.maybe(types.reference(types.late(() => User)))
})
.actions((self) => ({
setName(newName) {
self.name = newName
},
setUser(user) {
if (user === "") {
// When selected value is empty, set as undefined
self.user = undefined
} else {
self.user = user
}
},
toggle() {
self.done = !self.done
}
}))
```
--------------------------------
### Define Todo Model with Delayed Reference
Source: https://mobx-state-tree.js.org/intro/getting-started
This snippet illustrates defining a `Todo` model that references a `User` model. It uses `types.reference` combined with `types.late` to handle potential circular dependencies and `types.maybe` to allow the reference to be null.
```javascript
const Todo = types
.model({
name: types.optional(types.string, ""),
done: types.optional(types.boolean, false),
user: types.maybe(types.reference(types.late(() => User)))
})
.actions((self) => ({
setName(newName) {
self.name = newName
},
toggle() {
self.done = !self.done
}
}))
```
--------------------------------
### Display Computed Properties in React with MobX
Source: https://mobx-state-tree.js.org/intro/getting-started
Renders computed properties from an MST store into a React component. By using `observer`, the `TodoCounterView` component updates efficiently only when the `pendingCount` or `completedCount` values change. This example assumes `TodoView` and `AppView` are defined elsewhere and use the `observer` HOC.
```javascript
const TodoCounterView = observer((props) => (
))
```
--------------------------------
### Restore MST Model from Snapshot in JavaScript
Source: https://mobx-state-tree.js.org/intro/getting-started
Shows two methods to restore an MST model from a snapshot. The first creates a new instance using `.create()`, and the second applies the snapshot to an existing instance using `applySnapshot()`, triggering reconciliation.
```javascript
// 1st
const store = RootStore.create({
users: {},
todos: {
1: {
name: "Eat a cake",
done: true
}
}
})
// 2nd
applySnapshot(store, {
users: {},
todos: {
1: {
name: "Eat a cake",
done: true
}
}
})
```
--------------------------------
### Create Root Store with Maps in MobX State Tree
Source: https://mobx-state-tree.js.org/intro/getting-started
Defines a root store model (`RootStore`) that includes maps (`users` and `todos`) to hold collections of `User` and `Todo` instances, respectively. It utilizes `types.map` and `types.optional` to structure the store and initializes the store with an empty `users` map. This showcases how to build complex state structures.
```javascript
import { types } from "mobx-state-tree" // alternatively, `import { t } from "mobx-state-tree"`
const Todo = types.model({
name: types.optional(types.string, ""),
done: types.optional(types.boolean, false)
})
const User = types.model({
name: types.optional(types.string, "")
})
const RootStore = types.model({
users: types.map(User),
todos: types.optional(types.map(Todo), {})
})
const store = RootStore.create({
users: {} // users is not required really since arrays and maps are optional by default since MST3
})
```
--------------------------------
### Define MobX State Tree Models with Optional Types
Source: https://mobx-state-tree.js.org/intro/getting-started
Demonstrates the explicit way to define models in MobX State Tree using `types.optional` for attributes like `name` and `done`. This specifies the type and a default value, providing more control over attribute definition. It shows the underlying structure that the shortcut syntax represents.
```javascript
const Todo = types.model({
name: types.optional(types.string, ""),
done: types.optional(types.boolean, false)
})
const User = types.model({
name: types.optional(types.string, "")
})
```
--------------------------------
### Define MST Models for Todo and User
Source: https://mobx-state-tree.js.org/intro/getting-started
Creates MST models for 'Todo' and 'User' entities using `types.model`. 'Todo' has 'name' (string) and 'done' (boolean) properties, while 'User' has a 'name' (string) property. These models define the structure and default values for MST instances.
```javascript
import { types } from "mobx-state-tree"
const Todo = types.model({
name: "",
done: false
})
const User = types.model({
name: ""
})
```
--------------------------------
### Improve React Render Performance with Observer Components
Source: https://mobx-state-tree.js.org/intro/getting-started
Optimizes React component rendering by splitting the UI into smaller, observable components. Each `observer` component re-renders only when its specific observed data changes, preventing unnecessary re-renders of the entire application. Requires mobx-react-lite.
```javascript
const TodoView = observer((props) => (
))
```
--------------------------------
### Define MST Models and Actions in JavaScript
Source: https://mobx-state-tree.js.org/intro/getting-started
Defines MST models for Todo and User, and a RootStore with an addTodo action. Actions like `setName` and `toggle` modify the state of model instances. The `self` object refers to the current model instance within actions.
```javascript
const Todo = types
.model({
name: types.optional(types.string, ""),
done: types.optional(types.boolean, false)
})
.actions((self) => ({
setName(newName) {
self.name = newName
},
toggle() {
self.done = !self.done
}
}))
const User = types.model({
name: types.optional(types.string, "")
})
const RootStore = types
.model({
users: types.map(User),
todos: types.map(Todo)
})
.actions((self) => ({
addTodo(id, name) {
self.todos.set(id, Todo.create({ name }))
}
}))
```
--------------------------------
### MobX State Tree Reference Error Example
Source: https://mobx-state-tree.js.org/intro/getting-started
Illustrates the error message generated by MobX State Tree when an attempt is made to remove a model that is currently referenced by another model's computed property. This demonstrates the safety mechanism of references preventing data integrity issues.
```plaintext
[mobx-state-tree] Failed to resolve reference of type : '1' (in: /todos/1/user)
```
--------------------------------
### Define User Model with Identifier
Source: https://mobx-state-tree.js.org/intro/getting-started
This snippet demonstrates how to define a `User` model in MobX State Tree, specifying `id` as the unique identifier using `types.identifier`. Identifiers are required on creation and cannot be mutated.
```javascript
const User = types.model({
id: types.identifier,
name: types.optional(types.string, "")
})
```
--------------------------------
### Basic MobX-State-Tree Model and Store Example
Source: https://mobx-state-tree.js.org/index
This JavaScript example demonstrates how to define a model for a 'Tweet' with a body and read status, including a 'toggle' action. It then defines a 'TwitterStore' to hold an array of these tweets and initializes an instance. Finally, it shows how to listen for state changes using 'onSnapshot' and invoke the toggle action.
```javascript
import { t, onSnapshot } from "mobx-state-tree"
// A tweet has a body (which is text) and whether it's read or not
const Tweet = t
.model("Tweet", {
body: t.string,
read: false // automatically inferred as type "boolean" with default "false"
})
.actions((tweet) => ({
toggle() {
tweet.read = !tweet.read
}
}))
// Define the Twitter "store" as having an array of tweets
const TwitterStore = t.model("TwitterStore", {
tweets: t.array(Tweet)
})
// create your new Twitter store instance with some initial data
const twitterStore = TwitterStore.create({
tweets: [
{
body: "Anyone tried MST?"
}
]
})
// Listen to new snapshots, which are created anytime something changes
onSnapshot(twitterStore, (snapshot) => {
console.log(snapshot)
})
// Let's mark the first tweet as "read" by invoking the "toggle" action
twitterStore.tweets[0].toggle()
// In the console, you should see the result: `{ tweets: [{ body: "Anyone tried MST?", read: true }]}`
```
--------------------------------
### MobX-State-Tree: Apply Patch (JSON Example)
Source: https://mobx-state-tree.js.org/API/index
Demonstrates applying a JSON patch to modify a MobX-State-Tree. This example shows a simple patch that replaces a value at a specific path within the state tree. Ensure the patch conforms to the JSON Patch standard.
```json
{
"op": "replace",
"path": "/users/1/name",
"value": "Jane Doe"
}
```
--------------------------------
### Install mobx-state-tree
Source: https://mobx-state-tree.js.org/recipes/pre-built-form-types-with-mst-form-type
Ensures that mobx-state-tree version 5.0.0 or a compatible higher version is installed. This is a prerequisite for using the mst-form-type library.
```bash
npm install mobx-state-tree@^5.0.0
```
--------------------------------
### Install mst-form-type
Source: https://mobx-state-tree.js.org/recipes/pre-built-form-types-with-mst-form-type
Installs the mst-form-type library, which provides model types for form structures compatible with MobX State Tree. Ensure mobx-state-tree version 5.0.0 or higher is also installed.
```bash
npm install mst-form-type
```
--------------------------------
### Intercept MobX-state-tree Actions with addMiddleware
Source: https://mobx-state-tree.js.org/concepts/listeners
This example shows how to use `addMiddleware` to intercept and modify actions before they are applied to a MobX-state-tree store. It demonstrates a simple text replacement. Requires MST library.
```javascript
import { addMiddleware } from "mobx-state-tree"
addMiddleware(storeInstance, (call, next) => {
call.args[0] = call.args[0].replace(/tea/gi, "Coffee")
return next(call)
})
```
--------------------------------
### MST Runtime Type Error Example
Source: https://mobx-state-tree.js.org/intro/philosophy
This code illustrates a runtime type error in MST. It shows an attempt to create a store with data that does not match the defined type, resulting in an informative error message.
```text
[mobx-state-tree] Value '{"todos":[{"turtle":"Get tea"}]}' is not assignable to type: Store, expected an instance of Store or a snapshot like '{ todos: { title: string; done: boolean }[] }' instead.
```
--------------------------------
### Define a Model for Late Initialization (JavaScript)
Source: https://mobx-state-tree.js.org/tips/circular-deps
This snippet demonstrates how to define a basic model using `types.model` that can be referenced later. This is part of the setup for handling circular dependencies.
```javascript
export function LateStore() {
return types.model({
title: types.string
})
}
```
--------------------------------
### MobX State Tree Type Validation Error Example
Source: https://mobx-state-tree.js.org/intro/getting-started
Illustrates a common error scenario in MobX State Tree where an incorrect data type is provided during model instance creation. Attempting to assign a number to a boolean attribute (`done: 1`) results in a type validation error, demonstrating MST's type safety mechanism. This prevents inconsistent state by enforcing defined types.
```javascript
const eat = Todo.create({ name: "eat", done: 1 })
```
--------------------------------
### Identifier Refinement for Validation (JavaScript)
Source: https://mobx-state-tree.js.org/concepts/references
Illustrates how to use `types.refinement` with `types.identifier` to enforce specific naming conventions for identifiers. This example ensures that 'Car' model identifiers must start with 'Car_'.
```javascript
const Car = types.model("Car", {
id: types.refinement(types.identifier, identifier => identifier.indexOf("Car_") === 0)
})
```
--------------------------------
### Custom Reference Resolution Logic (JavaScript)
Source: https://mobx-state-tree.js.org/concepts/references
Shows how to implement custom logic for resolving references in MobX-state-tree using the `get` and `set` callbacks within `types.reference`. This example resolves a 'User' reference by name instead of ID.
```javascript
const User = types.model({
id: types.identifier,
name: types.string
})
const UserByNameReference = types.maybeNull(
types.reference(User, {
// given an identifier, find the user
get(identifier /* string */, parent: any /*Store*/) {
return parent.users.find(u => u.name === identifier) || null
},
// given a user, produce the identifier that should be stored
set(value /* User */) {
return value.name
}
})
)
const Store = types.model({
users: types.array(User),
selection: UserByNameReference
})
const s = Store.create({
users: [{ id: "1", name: "Michel" }, { id: "2", name: "Mattia" }],
selection: "Mattia"
})
```
--------------------------------
### IPatchRecorder Methods
Source: https://mobx-state-tree.js.org/API/interfaces/ipatchrecorder
This section details the methods available on the IPatchRecorder interface, including `resume`, `stop`, `replay`, and `undo`.
```APIDOC
## IPatchRecorder Methods
### `resume()`
- **Description**: Resumes patch recording.
- **Method**: `void`
- **Defined in**: src/core/mst-operations.ts:141
### `stop()`
- **Description**: Stops patch recording.
- **Method**: `void`
- **Defined in**: src/core/mst-operations.ts:140
### `replay(target?)`
- **Description**: Replays the recorded patches on a target node.
- **Method**: `void`
- **Parameters**:
- `target` (IAnyStateTreeNode, optional): The target state tree node to replay patches on.
- **Defined in**: src/core/mst-operations.ts:142
### `undo(target?)`
- **Description**: Undoes the last recorded patch on a target node.
- **Method**: `void`
- **Parameters**:
- `target` (IAnyStateTreeNode, optional): The target state tree node to undo patches on.
- **Defined in**: src/core/mst-operations.ts:143
```
--------------------------------
### MobX State Tree: Model Creation with `create` Method
Source: https://mobx-state-tree.js.org/API/interfaces/imodeltype
Demonstrates how to create an instance of a model type using the `create` method. This method accepts an optional snapshot and environment object to initialize the model. It's inherited from the base IType interface.
```typescript
create(snapshot?: ModelCreationType2 | ExcludeReadonly>, env?: any): this["Type"]
```
--------------------------------
### Dynamic Fields Actions and Usage (JavaScript)
Source: https://mobx-state-tree.js.org/recipes/pre-built-form-types-with-mst-form-type
Provides JavaScript code examples for interacting with dynamic fields in a form. It demonstrates how to add, remove, edit, get values, validate, and reset dynamic fields using their respective actions.
```javascript
form[id].fields.map(field => { ... })
form[id].addFields(field)
form[id].removeFields('id')
form[id].editField('id', 'key', 'value')
form[id].getValues() // get all dynamic field values, rarely used
form[id].valid() // valid all dynamic field, rarely used
form[id].reset() // reset all dynamic field, rarely used
```
--------------------------------
### Define and Use MST Models and Actions
Source: https://mobx-state-tree.js.org/intro/philosophy
This snippet demonstrates how to define a Todo model with a toggle action and a Store model containing an array of Todos. It shows creating an instance from a snapshot, listening to snapshot changes, and invoking an action.
```javascript
import { types, onSnapshot } from "mobx-state-tree"
const Todo = types
.model("Todo", {
title: types.string,
done: false
})
.actions((self) => ({
toggle() {
self.done = !self.done
}
}))
const Store = types.model("Store", {
todos: types.array(Todo)
})
// create an instance from a snapshot
const store = Store.create({
todos: [
{
title: "Get coffee"
}
]
})
// listen to new snapshots
onSnapshot(store, (snapshot) => {
console.dir(snapshot)
})
// invoke action that modifies the tree
store.todos[0].toggle()
// prints: `{ todos: [{ title: "Get coffee", done: true }]}`
```
--------------------------------
### Create Action Tracking Middleware v2 (mobx-state-tree)
Source: https://mobx-state-tree.js.org/API
An enhanced utility for creating action-based middleware, simplifying async process handling. It follows a clear flow: filter -> onStart -> (recursive inner actions) -> onFinish, regardless of whether actions are synchronous or asynchronous. This version is recommended over `createActionTrackingMiddleware`.
```typescript
import { IMiddlewareHandler, IActionTrackingMiddleware2Hooks } from "mobx-state-tree"
function createActionTrackingMiddleware2(middlewareHooks: IActionTrackingMiddleware2Hooks): IMiddlewareHandler {
// Implementation details...
return () => next => action => {
// Middleware logic
return next(action);
};
}
```
--------------------------------
### MST Model with Action and Instantiation Time Logging
Source: https://mobx-state-tree.js.org/concepts/trees
This example shows a simplified MST model 'TodoStore' with an 'addTodo' action. It includes a console log within the action to display the time elapsed since the model's instantiation, demonstrating how closures can be used within actions for private state or methods.
```javascript
const TodoStore = types
.model("TodoStore", {
/* props */
})
.actions((self) => {
const instantiationTime = Date.now()
function addTodo(title) {
console.log(`Adding Todo ${title} after ${(Date.now() - instantiationTime) / 1000}s.`)
self.todos.push({
id: Math.random(),
title
})
}
return { addTodo }
})
```
--------------------------------
### Create Action Tracking Middleware 2 (JS)
Source: https://mobx-state-tree.js.org/API/index
A convenience utility for creating action-based middleware that more easily supports asynchronous processes. The middleware follows a clear flow: for each action, if a filter passes, `onStart` is called, followed by recursive calls for inner actions, and finally `onFinish`. This flow remains consistent for both synchronous and asynchronous actions.
```javascript
import { createActionTrackingMiddleware2 } from "mobx-state-tree"
const middleware2 = createActionTrackingMiddleware2({
filter: action => action.name === "process",
onStart: action => console.log(`Started: ${action.name}`),
onFinish: action => console.log(`Finished: ${action.name}`),
})
```
--------------------------------
### Declare Todo Model and Create Instance (JavaScript)
Source: https://mobx-state-tree.js.org/concepts/trees
This snippet demonstrates how to define a data model named 'Todo' using `types.model` from the MobX State Tree library. It then shows how to create an instance of this model with initial state. The primary dependency is the `mobx-state-tree` library.
```javascript
import { types } from "mobx-state-tree" // alternatively, `import { t } from "mobx-state-tree"
// declaring the shape of a node with the type `Todo`
const Todo = types.model({
title: types.string
})
// creating a tree based on the "Todo" type, with initial data:
const coffeeTodo = Todo.create({
title: "Get coffee"
})
```
--------------------------------
### Define MST Model Views for Derived State (JavaScript)
Source: https://mobx-state-tree.js.org/intro/getting-started
Declares model views within a MobX State Tree model to compute derived properties like pending and completed counts. Views are read-only and can accept parameters, ensuring data integrity. They process the store's data without modifying it, preventing unintended state changes.
```javascript
const RootStore = types
.model({
users: types.map(User),
todos: types.map(Todo)
})
.views((self) => ({
get pendingCount() {
return Array.from(self.todos.values()).filter((todo) => !todo.done).length
},
get completedCount() {
return Array.from(self.todos.values()).filter((todo) => todo.done).length
},
getTodosWhereDoneIs(done) {
return Array.from(self.todos.values()).filter((todo) => todo.done === done)
}
}))
.actions((self) => ({
addTodo(id, name) {
self.todos.set(id, Todo.create({ name }))
}
}))
```
--------------------------------
### Listen to MobX-state-tree Patches with onPatch
Source: https://mobx-state-tree.js.org/concepts/listeners
Demonstrates how to use `onPatch` to track specific changes (patches) applied to a MobX-state-tree store. This provides granular information about modifications, including path, operation, and value. Requires MST library.
```javascript
import { onPatch } from "mobx-state-tree"
onPatch(storeInstance, patch => {
console.info("Got change: ", patch)
})
// Example of a patch:
// storeInstance.todos[0].setTitle("Add milk")
// prints:
// {
// path: "/todos/0",
// op: "replace",
// value: "Add milk"
// }
```
--------------------------------
### Basic Model and Store with References (JavaScript)
Source: https://mobx-state-tree.js.org/concepts/references
Defines a 'Todo' model with an identifier and a 'TodoStore' that uses an array of 'Todo' models and a reference to a selected 'Todo'. Demonstrates creating a store instance and accessing a referenced object's property.
```javascript
const Todo = types.model({
id: types.identifier,
title: types.string
})
const TodoStore = types.model({
todos: types.array(Todo),
selectedTodo: types.reference(Todo)
})
// create a store with a normalized snapshot
const storeInstance = TodoStore.create({
todos: [
{
id: "47",
title: "Get coffee"
}
],
selectedTodo: "47"
})
// because `selectedTodo` is declared to be a reference, it returns the actual Todo node with the matching identifier
console.log(storeInstance.selectedTodo.title)
// prints "Get coffee"
```
--------------------------------
### Define MST SnapshotOrInstance Type with Example
Source: https://mobx-state-tree.js.org/API
Demonstrates the `SnapshotOrInstance` type in MST, which represents either the input snapshot or the runtime instance of a model. This is useful for setter actions that can accept both formats. The example shows a `ModelB` with an `innerModel` property and a `setInnerModel` action.
```typescript
const ModelA = types.model({
n: types.number
})
const ModelB = types.model({
innerModel: ModelA
}).actions(self => ({
// this will accept as property both the snapshot and the instance, whichever is preferred
setInnerModel(m: SnapshotOrInstance) {
self.innerModel = cast(m)
}
}))
```
--------------------------------
### Fetch Projects using MST Flow (JavaScript)
Source: https://mobx-state-tree.js.org/concepts/async-actions
Demonstrates an asynchronous action using `flow` and generators in MobX State Tree to fetch GitHub projects. It includes state management for pending, done, and error states, and handles promise resolution and rejection.
```javascript
import { flow } from "mobx-state-tree"
const Store = types
.model({
githubProjects: types.array(types.frozen),
state: types.enumeration("State", ["pending", "done", "error"])
})
.actions((self) => ({
fetchProjects: flow(function* fetchProjects() {
// <- note the star, this a generator function!
self.githubProjects = []
self.state = "pending"
try {
// ... yield can be used in async/await style
self.githubProjects = yield fetchGithubProjectsSomehow()
self.state = "done"
} catch (error) {
// ... including try/catch error handling
console.error("Failed to fetch projects", error)
self.state = "error"
}
})
}))
const store = Store.create({})
// async actions will always return a promise resolving to the returned value
store.fetchProjects().then(() => {
console.log("done")
})
```
--------------------------------
### getLivelinessChecking
Source: https://mobx-state-tree.js.org/API
Gets the current mode for liveliness checking. This mode determines how liveliness violations are handled.
```APIDOC
## GET /mobx-state-tree/getLivelinessChecking
### Description
Returns the current liveliness checking mode.
### Method
GET
### Endpoint
/mobx-state-tree/getLivelinessChecking
### Response
#### Success Response (200)
- **mode** (LivelinessMode) - The current liveliness checking mode ('warn', 'error', or 'ignore').
### Response Example
```json
{
"mode": "warn"
}
```
```
--------------------------------
### Get Path Parts of MST Node
Source: https://mobx-state-tree.js.org/API
Retrieves the path of a MobX State Tree object as an array of unescaped string segments.
```typescript
getPathParts(target: IAnyStateTreeNode): string[]
```
--------------------------------
### IMiddlewareEvent Interface
Source: https://mobx-state-tree.js.org/API/interfaces/imiddlewareevent
Details the properties and hierarchy of the IMiddlewareEvent interface.
```APIDOC
## IMiddlewareEvent
### Description
Represents an event that can be intercepted by middleware in MobX-State-Tree. It extends `IActionContext` and provides additional properties specific to middleware events.
### Hierarchy
* IActionContext
↳ **IMiddlewareEvent**
### Properties
#### `allParentIds`
- **allParentIds** (number[]) - Required - Id of all events, from root until current (excluding current).
#### `args`
- **args** (any[]) - Inherited from `IActionContext` - Event arguments in an array (action arguments for actions).
#### `context`
- **context** (IAnyStateTreeNode) - Inherited from `IActionContext` - Event context (node where the action was invoked).
#### `id`
- **id** (number) - Inherited from `IActionContext` - Event unique id.
#### `name`
- **name** (string) - Inherited from `IActionContext` - Event name (action name for actions).
#### `parentActionEvent`
- **parentActionEvent** (IMiddlewareEvent | undefined) - Inherited from `IActionContext` - Parent action event object.
#### `parentEvent`
- **parentEvent** (IMiddlewareEvent | undefined) - Parent event object.
#### `parentId`
- **parentId** (number) - Parent event unique id.
#### `rootId`
- **rootId** (number) - Root event unique id.
#### `tree`
- **tree** (IAnyStateTreeNode) - Inherited from `IActionContext` - Event tree (root node of the node where the action was invoked).
#### `type`
- **type** (IMiddlewareEventType) - Event type.
```
--------------------------------
### Get Path of MST Node
Source: https://mobx-state-tree.js.org/API
Returns the hierarchical path of a given MobX State Tree object within the state tree as a string.
```typescript
getPath(target: IAnyStateTreeNode): string
```
--------------------------------
### Get Identifier of MST Node
Source: https://mobx-state-tree.js.org/API
Returns the normalized string identifier for a given MobX State Tree node. Returns null if the node does not have an identifier.
```typescript
getIdentifier(target: IAnyStateTreeNode): string | null
```
--------------------------------
### IAnyModelType Methods
Source: https://mobx-state-tree.js.org/API/interfaces/ianymodeltype
Describes the methods available for the IAnyModelType.
```APIDOC
## Methods
### actions
- **actions** (function) - Returns: IModelType. Defines actions for the model.
### create
- **create** (snapshot? - ModelCreationType2 | ExcludeReadonly>, env? - any) - Returns: this["Type"]. Creates an instance for the type given an snapshot input.
### describe
- **describe** () - Returns: string. Gets the textual representation of the type as a string.
### extend
- **extend** (function) - Returns: IModelType. Extends the model.
### is
- **is** (thing - any) - Returns: thing is ModelCreationType2 | this["Type"]. Checks if a given snapshot / instance is of the given type.
### named
- **named** (newName - string) - Returns: IModelType.
### postProcessSnapshot
- **postProcessSnapshot** (function) - Returns: IModelType.
### preProcessSnapshot
- **preProcessSnapshot** (function) - Returns: IModelType.
### props
- **props** (props - PROPS2) - Returns: IModelType, any, any, any>.
```
--------------------------------
### Generate MST Models from JSON using transform.now.sh
Source: https://mobx-state-tree.js.org/tips/more-tips
A helpful online service for generating MobX-State-Tree (MST) models directly from JSON data. This simplifies the process of defining your state structure based on existing data formats.
--------------------------------
### Get Liveliness Checking Mode
Source: https://mobx-state-tree.js.org/API
Returns the current mode for liveliness checking in MobX State Tree. This mode determines how deviations from expected state are handled.
```typescript
getLivelinessChecking(): LivelinessMode
```
--------------------------------
### Inject Environment Utilities with MobX State Tree
Source: https://mobx-state-tree.js.org/concepts/dependency-injection
Demonstrates injecting utilities like a logger into a MobX state tree. The injected object is accessible via `getEnv(self)` within model actions. This improves testability by allowing mock utilities to be provided during store creation.
```javascript
import { types, getEnv } from "mobx-state-tree"
const Todo = types
.model({
title: ""
})
.actions(self => ({
setTitle(newTitle) {
// grab injected logger and log
getEnv(self).logger.log("Changed title to: " + newTitle)
self.title = newTitle
}
}))
const Store = types.model({
todos: types.array(Todo)
})
// setup logger and inject it when the store is created
const logger = {
log(msg) {
console.log(msg)
}
}
const store = Store.create(
{
todos: [{ title: "Grab tea" }]
},
{
logger: logger // inject logger to the tree
}
)
store.todos[0].setTitle("Grab coffee")
// prints: Changed title to: Grab coffee
```
--------------------------------
### ReferenceOptionsGetSet.get Method (TypeScript)
Source: https://mobx-state-tree.js.org/API/interfaces/referenceoptionsgetset
The 'get' method of ReferenceOptionsGetSet retrieves a reference based on an identifier and its parent node. It is defined in src/types/utility-types/reference.ts.
```typescript
get(identifier: ReferenceIdentifier, parent: IAnyStateTreeNode | null): ReferenceT;
```
--------------------------------
### IPatchRecorder Properties
Source: https://mobx-state-tree.js.org/API/interfaces/ipatchrecorder
This section details the properties of the IPatchRecorder interface, including `inversePatches`, `patches`, `recording`, and `reversedInversePatches`.
```APIDOC
## IPatchRecorder Properties
### `patches`
- **Type**: `ReadonlyArray`
- **Description**: An array of recorded patches.
- **Defined in**: src/core/mst-operations.ts:136
### `inversePatches`
- **Type**: `ReadonlyArray`
- **Description**: An array of recorded inverse patches.
- **Defined in**: src/core/mst-operations.ts:137
### `reversedInversePatches`
- **Type**: `ReadonlyArray`
- **Description**: An array of reversed inverse patches.
- **Defined in**: src/core/mst-operations.ts:138
### `recording`
- **Type**: `boolean`
- **Description**: A boolean indicating whether recording is currently active.
- **Defined in**: src/core/mst-operations.ts:139
```
--------------------------------
### Get Unique Node ID in MST
Source: https://mobx-state-tree.js.org/API
Returns a unique numerical identifier for a specific MobX State Tree instance. This ID is distinct from any custom instance identifiers.
```typescript
getNodeId(target: IAnyStateTreeNode): number
```
--------------------------------
### Create Model with Identifier Type
Source: https://mobx-state-tree.js.org/API/index
Provides an example of creating a model with an `types.identifier` property. Identifiers are crucial for unique referencing and reconciliation within MST.
```typescript
import { types } from "mobx-state-tree"
const Todo = types.model("Todo", {
id: types.identifier,
title: types.string
})
```
--------------------------------
### Listen to MobX Observables with autorun
Source: https://mobx-state-tree.js.org/concepts/listeners
This snippet demonstrates how to use MobX's `autorun` function to react to changes in observable properties within a MobX-state-tree store. It requires the 'mobx' library.
```javascript
import { autorun } from "mobx"
autorun(() => {
console.log(storeInstance.selectedTodo.title)
})
```
--------------------------------
### Get Parent of MST Node by Type
Source: https://mobx-state-tree.js.org/API
Finds and returns the nearest ancestor of a MobX State Tree node that matches a specified type. Throws an error if no such parent is found.
```typescript
getParentOfType(target: IAnyStateTreeNode, type: IT): IT["Type"]
```
--------------------------------
### Listen to MobX-state-tree Actions with onAction
Source: https://mobx-state-tree.js.org/concepts/listeners
This snippet illustrates how to use `onAction` to be notified whenever an action is invoked on a MobX-state-tree store. It provides details about the action's name and arguments. Requires MST library.
```javascript
import { onAction } from "mobx-state-tree"
onAction(storeInstance, call => {
console.info("Action was called:", call)
})
// Example of an action call:
// storeInstance.todos[0].setTitle("Add milk")
// prints:
// {
// path: "/todos/0",
// name: "setTitle",
// args: ["Add milk"]
// }
```
--------------------------------
### Get Current Running Action Context
Source: https://mobx-state-tree.js.org/API
Returns the context of the currently executing MobX State Tree action. If no action is currently running, it returns `undefined`. This is useful for middleware and debugging.
```typescript
import { getRunningActionContext, IActionContext } from "mobx-state-tree";
function getCurrentAction(): IActionContext | undefined {
return getRunningActionContext();
}
```
--------------------------------
### MobX State Tree: Snapshot Pre-Processing with `preProcessSnapshot`
Source: https://mobx-state-tree.js.org/API/interfaces/imodeltype
Illustrates the `preProcessSnapshot` method, which allows for transforming a snapshot before it's used to create or update a model instance. This is useful for data validation or normalization.
```typescript
preProcessSnapshot(fn: (snapshot: NewC) => WithAdditionalProperties>): IModelType
```
--------------------------------
### Get Environment of MST Node
Source: https://mobx-state-tree.js.org/API
Retrieves the environment associated with a MobX State Tree node. This is useful for dependency injection. Access to the root's environment in child nodes is only available after 'afterAttach'.
```typescript
getEnv(target: IAnyStateTreeNode): T
```
--------------------------------
### Get MST Parent of Specific Type
Source: https://mobx-state-tree.js.org/API/index
Finds and returns the nearest ancestor node of a specified MST type. This is useful for navigating up the tree to find a parent with a particular model definition.
```typescript
const specificParent = getParentOfType(myStateTreeNode, MyParentModel)
```