Search code examples
react-nativemobxmobx-state-tree

How to create types.array in MST from external api - always returning proxy not object


I'm fetching data from external API, and want to store it in MST store as array. But the result is always proxy, not the object I wanted.

This is result from API:

(4) [Object, Object, Object, Object]
0:Object
id:1
name: "Foobar"
created_at: "2019-04-27 09:09:29"
updated_at:null
deleted_at:null
__proto__:Object
.........

This is my store:


const TypesModel = types.model({
  name: types.maybe(types.string),
  created_at: types.maybe(types.string)
});

export const TransactionTypeStore = types
  .model("TransactionTypeStore", {
    transaction_types: types.optional(types.array(TypesModel), [])
  })
  .actions(self => ({
    getTypes: flow(function*(token) {
      try {
        const res = yield typesApi
          .headers({ Authorization: `Bearer ${token}` })
          .get()
          .json();

        console.log("result", res);

        self.transaction_types = res;

        // res.map(data => {
        //   self.transaction_types.push(data);
        // });
      } catch (err) {
        console.log(err);
      }
    })
  }));

And this is console.log of my MST store:

transaction_types:Proxy
[[Handler]]:Object
[[Target]]:Array(4)
0:ObjectNode
1:ObjectNode
2:ObjectNode
3:ObjectNode
$treenode:ObjectNode
length:4
toJSON:function toJSON()
Symbol(mobx administration):ObservableArrayAdministration
__proto__:Array(0)
[[IsRevoked]]:false
.........

Does anyone know how to deal with this kind of problem?


Solution

  • How does your res object look like, it should be an array of { name, created_at } objects - nothing more nothing less, is it? Also transaction_types will never be a mere array - types.array is a complex MST type, it has some array methods, but it's not an array. It's an observable array and you should treat it accordingly.

    Also check this video tutorial by Michel Weststrate himself: Use observable objects, arrays, and maps to store state in MobX to get a better grip on the concept (create an account, it's free).