Passing array of objects in sendEvent
musicbyjing opened this issue · 2 comments
I'm having a hard time passing an array of objects to the widget component file. I can console.log
the array, but as soon as I try to operate on it (like adding .map
, or even indexing) it gives me Cannot read property ___ of undefined
.
Is passing an array of objects through sendEvent a supported operation? I can't seem to find any examples that do this. Thanks!
Hi @musicbyjing.
Passing only an array as value indeed behaves somewhat unexpected, as Dashbling will assign props "0", "1" etc on the React component so this is not very convenient to work with. Instead, it's better to send an object, where one of the values of the object is an array:
sendEvent("my-event", { names: ["foo", "bar"] });
Then you can use the array in your component as you would expect:
export const MyWidget = props => (
<Widget>
<p>{props.names && props.names.join(",")}</p>
</Widget>
);
The only gotcha here is that when your component renders before the first event is received, the props will be undefined so you need to handle this.
Checking if the props are available is a common pattern in Dashbling widgets.
I've thought about handling this in Dashbling by for example not rendering the widget if the data is not yet available, but that too might be unexpected as it's perfectly valid to render a widget in many cases even when there's no data yet.
Hope this is helpful.
Cheers, Pascal
Hi Pascal, thanks so much for the quick reply! The problem I had was due to your second point, which I solved by calling if (!props) return null
, which I suppose is the same principle. I have another question but will close this issue, thanks again.