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

2k views Asked by At

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.

2

There are 2 answers

1
Prashant Gupta On BEST ANSWER

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)
      }
    })
0
Coder Nr 23 On

I needed to do this because I receive object of a well defined type, but that type contains a config field, that can be any json.

I managed to do it in MST by defining:

export const AnyJsonValue = types.union(
    types.string,
    types.number,
    types.integer,
    types.Date,
    types.boolean,
    types.map(types.late(() => JsonValue)),
    types.array(types.late(() => JsonValue)),
    types.undefined,
    types.null
);

And then using it like this:

export const MyObject = types.model("MyObject", {
        uuid: types.identifier,
        name: types.string,
        config: types.maybeNull(types.map(AnyJsonValue)),
        ...
});

If you have some restrictions, you can still set them. For example, if you want config to be either null, or a dict with any json nested (so config can't be a literal or array, but can be a dict containing them), you can use the type: t.maybeNull(t.map(JsonValue)).