Accessing data in "model" from custom component using javascript

So, I tried the React thing. I gave it a good, college try. In fact, I got it working in a lot of different apps. But. It's just inconsistent. Can't get it to reliably work. Can't easily debug. Just tired of messing with it.

So. Now. I just want to use javascript in the Custom Component. So far, so much easier. Except.

I can't access an input parameter that is an array of objects. I can access the other input parameters, and I can see that the array is, in fact, an array of objects. But, if I try to use the "length" property of javascript arrays, or if I try to index into the array, fail.

What's happening?

The first screenshot shows that it recognizes that it's an array of objects.

The second screenshot shows that when I try to access something in one of the objects in the array, it barfs.

The third screenshot shows the data that is the input for the custom component.

Any ideas what I'm doing wrong or how I can fix it?

Thanks!

2 issues:

  • HTML output should only include strings. It looks likeallItems, model.columnLabel and Model.columnDescription are not strings; we do our best to stringify for you, but as you can see here we're falling back to [Object object]. I'd start by wrapping those things in JSON.stringify and improving from there.
  • Your component is blowing up probably because of unsafe access on an undefined value. Try using the safe access operator: model.itemsList?.[0]?.companyName || ''.
2 Likes

Not sure why the ?. operator worked, since it seems that's intended to allow a nicer error handling when an invalid index or invalid key is used, and model.itemsList[0].companyName is valid.

I don't actually have a problem with the html - columnLabel and columnDescription are both strings. I was just trying to illustrate the problem in the first screenshot - it wasn't what I was trying to accomplish.

The first screenshot was supposed to illustrate that the script could detect that allItems was in fact an array of objects. My problem was accessing the data in the array as seen in the second screenshot.

I'm still not sure why that doesn't work, but you gave me a workaround, so I'm back in business, and that's good enough for me! Thanks for the fast reply!

Hello,
Just to give you an idea why it failed when you don't have ?. in the getter.
In your third image, you show the model being injects with data from columnItems. I don't know how the data being pull but at one point columnItems.value must equals to one of the following: undefined, null, '', []

So at that moment in time, model.itemsList[0] will give you an error. The reason ?. works because it will return undefined instead of throwing an exception. To test it out, you can do console.log(model.itemsList) to see the output in browser's dev tool.

3 Likes

Oh that makes sense! The data is coming from a REST API query to an outside source, so it is empty until the data comes in. Thanks!

1 Like