Search code examples
reactjsmobxmobx-reactmobx-state-tree

Is there a way to save dynamic JSON into Mobx State Tree?


I was using Redux before and saving dynamic JSON into the store was quite easy. I was thinking, how can we do the same in the Mobx-State-Tree, without actually defining the model structures.

.model({
    data:types.array(...)
)}

I was trying, but again I need to define the JSON array structure into it.


Solution

  • The whole idea for using mobx state tree is to define implicit data types into your application.

    But if for some reason you want to save JSON without defining is to convert it into a string using JSON.stringify({...})

    And the model will be actually a string

    .model({
        data:types.string
    )}
    

    Then you can use actions to save JSON into it

    .actions((self) => ({
       saveJSON(jsonData){
            self.data = JSON.stringify(jsonData)        
          }
    })
    

    You can then use this JSON anywhere by calling store.getJson property with JSON.parse() using view

       views((self) => ({
          get getJson(){
             return JSON.parse(self.data)
          }
        })