Search code examples
reactjsmobxmobx-state-tree

How to storeimage from input in mobx-state-tree model?


I am trying to find a solution how I can store files in mobx-state-tree models. But mobx-state-tree don't have something like types.file. Does anyone know how to deal with this kind of problem? Or I have to find another solution?


Solution

  • If someone still wonders how to deal with input type="file" data, I ended up using volatile on my form model:

    const EditForm = types
      .model({ /*...*/ })
      .volatile(() => ({
        pictureFile: null
      }))
      .actions(self => ({
        setPicture(file) {
          self.pictureFile = file;
        },
        save: flow(function*() {
          let formData = new FormData();
          formData.append('picture', self.picture);
          // ...
        })
      }))
    

    In your change handler of the file input:

    onFileInputChange(e) {
      editFormStore.setPicture(e.target.files[0])
    }