redgeoff / mson

🏗️MSON Lang: Generate an app from JSON
Apache License 2.0
470 stars 33 forks source link

Using mson CollectionField Programmatically #179

Open joshglenn opened 5 years ago

joshglenn commented 5 years ago

So, I'm trying to use the CollectionField to manually create some records and store them to localStorage. I'm seeing behavior that I don't quite understand.

For instance. This works to add ten items to the collection:

export async function testCollectionFieldWithForLoop() {   
  for (let index = 0; index < 10; index++) {
    let field = compiler.newComponent(TranslationCollectionField);
    const form = field.get('form');
    const form1 = field.addForm({
      form,
      values: {

        fromWord: 'lorem',
        toWord: 'ipsum',
        fromLangId: 'latin',
        toLangId: 'lorem', 

      }
    }); 
    await field._saveForm(form);    
  }

}

the following, however, only adds one item:

let field = compiler.newComponent(TranslationCollectionField);
export async function testCollectionFieldWithForLoop() {   
  for (let index = 0; index < 10; index++) {
    const form = field.get('form');
    const form1 = field.addForm({
      form,
      values: {

        fromWord: 'lorem',
        toWord: 'ipsum',
        fromLangId: 'latin',
        toLangId: 'lorem', 

      }
    }); 
    await field._saveForm(form);    
  }

}

And the following does not add any items into localStorage

export async function testCollectionFieldWithForLoop() {   
  for (let index = 0; index < 10; index++) {
    let field = compiler.newComponent(TranslationCollectionField);
    const form = field.get('form');
    const form1 = field.addForm({
      form,
      values: {

        fromWord: 'lorem',
        toWord: 'ipsum',
        fromLangId: 'latin',
        toLangId: 'lorem', 

      }
    }); 
    await field.save();    
  }

}

I'm sure I must be doing something wrong, but have no idea what. Any suggestions?

joshglenn commented 5 years ago

Ok. So, in the third example, it wasn't passing validation (the first example bypasses validation by using _saveForm() instead of save()). I had accidentally marked another (unused) field as required in my mson component definition.

Now, that just leaves the question about my 2nd example. Right now, things are only working when I declare a new CollectionField for every item I add. Any ideas what I might be doing wrong?