mobx-state-tree: How to clone a model that includes references?
Asked Answered
H

1

6

I'm trying to clone a model that references another model, but I get: Error: [mobx-state-tree] Failed to resolve reference 'H1qH2j20z' to type 'AnonymousModel' (from node: /usualCustomer)... in the clone. The original resolves okay.

Here are my models:

const Job = types.model({
    id: types.optional(types.identifier(types.string), shortid.generate()),
    jobNumber: types.optional(types.string, ''),
    description: '',
    usualCustomer: types.maybe(types.reference(Customer)),
  })

const Customer = types.model({
    id: types.optional(types.identifier(types.string), shortid.generate()),
    name: types.optional(types.string, 'New customer'),
  })

This function shows the problem:

editJob = job => {
    console.log('Original', job)
    var newClone = clone(job)
    console.log('Clone', newClone)
}
Hemline answered 18/5, 2018 at 20:28 Comment(0)
G
0

Did you try also to change the identifier of the node you want to clone ?

i'm not sure if it will work. but when you clone the job node, i think the new created job newJob act as a reference to the cloned job, give it a try anyway :

let jobFromSnap = getSnapshot(job);  
let newJob = Job.create({...jobFromSnap, id : "NEW_ID_HERE" }) ;
Grieve answered 1/3, 2019 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.