1

I was used lodash function like that _.CloneDeep for object array copy but I need shallow copy of this array Please consider the following code:

 @observable.ref trades: Array<TradeType> = [];
 @action attachNewTrade = (trade: TradeType): Array<TradeType> => {
    let newTrades = _.CloneDeep(this.trades)
    newTrades.push(trade)
    this.trades = newTrades
  }

I am using React+Mobx in this project Especially I need Observable function for this, not toJSON of immutable.js

Zheng Guo
  • 21
  • 5

2 Answers2

1

This is not specific to mobx

 @observable.ref trades: Array<TradeType> = [];
 @action attachNewTrade = (trade: TradeType): Array<TradeType> => {
    this.trades = [...this.trades, trade]
 }

The reason you need to copy is that React can't detect internal change of objects/array, so you need to change the reference to notify React that something is changed.

If you want solution of more mobx way, please check https://github.com/mobxjs/mobx/issues/1489

wang
  • 1,660
  • 9
  • 20
  • So this doesn't answer his question? He specifically asked for a mobx solution but a link is not an answer. – Rob Oct 22 '18 at 02:52
1

I was having the same issue and I solved it with mobx's toJS: https://mobx.js.org/refguide/tojson.html

MADPT
  • 97
  • 2
  • 12