Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 641
Nico Audy Avatar asked Jul 28 '26 09:07

Nico Audy


1 Answers

its similar to TypeScript, only you are using Mobx .MODEL

So lets say we want to create a ToDo list, which array that has id: number, name: string, isDone: boolean.

You first Define this Interface using Mobx .model, like this:

const singleToDoItem = types.model({
    id: types.number,
    name: types.string,
    isDone: types.boolean
})

we then create an Actual Store, with ARRAY as a type (you can also use .optional) AND then put the singleToDoItem inside the types.array(singleToDoItem), so it looks like this:

const myStore = types.model({
    list: types.array(singleToDoItem)
})

FINAL CODE will look like this:

const singleToDoItem = types.model({
    id: types.number,
    name: types.string,
    isDone: types.boolean })

const myStore = types.model({
    toDoList: types.array(singleToDoItem) })

I made a video on how to do this on my YouTube channel.

like image 91
fruitloaf Avatar answered Jul 30 '26 08:07

fruitloaf