2
votes

From the docs I have understood that the supported complex types for mobx-state-tree are

  • types.model(properties, actions) Defines a "class like" type, with properties and actions to operate on the object.
  • types.array(type) Declares an array of the specified type.
  • types.map(type) Declares a map of the specified type.

However I want to load a type of "File" from the element using the HTML element <input type="file" /> and maintain it in my state tree. Is this possible ?

2

2 Answers

2
votes

MST is made for working (mostly) with serializable data. If your file isn't big, you can base64 it and save as types.string. Otherwise, types.volatile is the best way to treat non serializable blobs. Here are the relevant docs: https://mobx-state-tree.js.org/concepts/volatiles

0
votes

I made a solution to this issue by having a global object called blobMap. The blobMap is a mapping of a string ("blobId") to a Blob object. Then I store the blobId in the mobx-state-tree as a simple types.string, and when I need the actual Blob I call blobMap[blobId]

Of course the blob will only be valid in a specific session on the page, so if you refresh the page and this blobId is still in your tree, you can check to see if that blobId is still in the blobMap and prompt the user to reload it if needed

I use the term Blob/File sort of interchangeably here (a File is a type of Blob) so you can replace any usage of blob in this answer with file and it should be valid.