0

I'm using Vaadin Flow, version 22. I'm trying to integrate a web component that has an attribute that require an array of objects, and these objects use a Javascript Date.

To give you an idea, here is how you'd be supposed to use it in a Javascript environment:

import {LitElement, html} from 'lit';
import {customElement} from 'lit/decorators.js';
import '@third-party/third-party-element';

@customElement('new-element')
export class NewElement extends LitElement {
  render() {
    const data = [
        {value: "someValue1", date: new Date(2022,1,1)},
        {value: "someValue2", date: new Date(2022,1,2)}
    ];
    return html`
      <third-party-element data='${data}'></third-party-element>
    `;
  }
}

I haven't figured out how to pass this sort of data from Java code to the LitElement. So far I'm stuck with the code below (in reality, marshalling my data into JSON via Jackson), but if I try to use a date in there, it'll just be an ISO8601 string, not an actual Javascript Date...

package org.mycompany;

import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.littemplate.LitTemplate;

@Tag("third-party-element")
@NpmPackage(value = "@third-party/third-party-element", version = "1.0.0")
@JsModule("@third-party/third-party-element/third-party-element.js")
public class ThirdPartyElement extends LitTemplate {

  public ThirdPartyElement() {
    getElement().setAttribute("data", "[{\"value\": \"someValue1\", \"date\": \"???\"}, {\"value\": \"someValue2\", \"date\": \"???\"}]");
  }
}

Can you help me figure out how to do this ?

Thanks in advance !

EDIT : After exploring Vaadin code I realized there was no built-in way of automatically parsing my data into Dates. So I ended up making a JS class extending the third party class, and added a method setData to it that would parse the incoming JSON data and convert every ISO8601 string into a Date, and then do this.data = myNewData;. And from the corresponding component in Java I called

getElement().callJsFunction("setData", this.objectMapper.writeValueAsString(myData));
  • Try passing the data as a JS property rather than an HTML attribute, you can do that using the `.data=${}` syntax. Attributes can only be strings but properties can be any JS object https://lit.dev/docs/templates/expressions/#property-expressions – Alan Dávalos Feb 18 '22 at 07:03
  • Ah I see, thanks for the info @AlanDávalos, I'll try that! – FlorianAgilap Feb 18 '22 at 09:42

1 Answers1

0

In your Java code, you should be able to convert the ISO string to LocalDate using:

LocalDate date = LocalDate.parse(isoString);
Tatu Lund
  • 9,949
  • 1
  • 12
  • 26