{"library":"mst-middlewares","title":"MobX-State-Tree Prebuilt Middlewares","description":"mst-middlewares provides a collection of prebuilt middlewares for MobX-State-Tree (MST), primarily serving as examples and starting points for developers to create their own custom MST middlewares. Originally part of the `mobx-state-tree` monorepo, it was extracted into its own package to keep the core MST library small. The package is currently at version 6.1.0 and appears to have a release cadence driven by contributions and fixes, with a recent major bump to v6.0.0. Key differentiators include its direct lineage from the official MST repository, offering basic but functional examples like action logging and transactional rollbacks, and encouraging direct modification or copy-pasting of its source for specific project needs rather than relying on them as fully-fledged, heavily-supported features. Developers are encouraged to read the source code to understand how to implement custom middleware for MST's event system.","language":"javascript","status":"active","last_verified":"Thu Apr 23","install":{"commands":["npm install mst-middlewares"],"cli":null},"imports":["import { simpleActionLogger } from 'mst-middlewares';","import { actionLogger } from 'mst-middlewares';","import { atomic } from 'mst-middlewares';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { types, addMiddleware, flow } from 'mobx-state-tree';\nimport { atomic } from 'mst-middlewares';\n\nconst delay = (ms: number) => new Promise(res => setTimeout(res, ms));\n\nconst TestModel = types\n  .model({\n    z: types.number,\n  })\n  .actions((self) => {\n    // Example of adding middleware directly\n    addMiddleware(self, atomic);\n\n    return {\n      inc: flow(function* (x: number) {\n        console.log(`Initial z: ${self.z}`);\n        yield delay(2);\n        self.z += x;\n        console.log(`z after first increment: ${self.z}`);\n        yield delay(2);\n        self.z += x;\n        console.log(`z after second increment: ${self.z}`);\n        throw new Error(\"Oops, something went wrong!\");\n      }),\n    };\n  });\n\nconst m = TestModel.create({ z: 1 });\n\nm.inc(3).catch((error: Error) => {\n  console.error(`Caught error: ${error.message}`);\n  console.log(`z after failed action (should be rolled back): ${m.z}`); // Expected: 1\n});\n","lang":"typescript","description":"This quickstart demonstrates the `atomic` middleware, which ensures that any modifications made within a synchronous or asynchronous action are rolled back if the action fails. It shows how to use `addMiddleware` on a model instance and verifies that the state (`m.z`) returns to its initial value after a `flow` action throws an error.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}