What is the best practice for updating the state of a web component in a manner that can be tracked by history with vaadin-router?

I have a straightforward LitElement custom component that I would like to incorporate an "editing" state into. Although I already possess all the necessary information from the server, I am hesitant to introduce a new component solely for displaying an editing screen or refreshing the current component. However, I do wish to ensure that when a user hits the back button, they exit the editing state. Balancing these requirements has proven challenging for me.

Here's a simple example:

@customElement('my-element')
class MyElement extends LitElement {

  @property({ attribute: false }) private _editing = false;
  @property({ attribute: false }) private _data!: Data;

  public connectedCallback() {
    super.connectedCallback();
    // Loading stuff..
  }

  public render() {
    return this._editing
      ? html`
          <editing-control .data=${this._data}></editing-control>
        `
      : html`
          <details-control .data=${this._data}></details-control>
          <button @click=${this._onEditClick}>Edit</button>
        `;
  }

  private _onEditClick(e: Event) {
    this._editing = true;
  }
}

It's worth noting that I'm utilizing Vaadin router for routing, and I've encountered issues with the following approaches:

  • When the edit button adds #editing to the URL (either as a link or by modifying the location using Route.go or window.location.href), the router reconnects the component, leading to data reloads and state resets.
  • Any attempts to listen for 'popstate' notifications occur after vaadin-router actions, resulting in changes to the previous location before I can intervene.
  • Utilizing onBeforeLeave doesn't allow me to distinguish between a back navigation attempt and a valid request to navigate to a different page from the menu.

Answer №1

It is likely that your routes configuration resembles something like this:

{
  path: '/foo',
  component: 'my-foo-component'
}

To improve it, consider using action instead of component. In the action, make sure to return the same instance of the component.

const fooElement = document.createElement('my-foo-component');
....

{
  path: '/foo',
  action: () => fooElement;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When package.json is imported, files are not compressed

Currently, I am working on developing a cli package and when it comes to displaying the version, I am utilizing the version imported from package.json. Upon running tsc, the structure of the dist folder appears as follows: /dist --/package.json --/README. ...

Exploring how to traverse a <router-outlet> within its container

I am attempting to switch the active component within a from its parent. After observing how Ionic achieves this, I believe it should resemble the following (simplified): @Component({ template: '<router-outlet></router-outlet>' } ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Personalized Carousel using Ng-Bootstrap, showcasing image and description data fields

I have been working on customizing an Angular Bootstrap Carousel and have managed to successfully change the layout. I now have two columns - with the image on the right and text along with custom arrows on the left. My goal is twofold: First, I am lookin ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...

Obtaining parameter types for functions from deeply nested types

I'm currently facing a challenge involving deeply nested parameters. When dealing with non-nested parameters, everything functions smoothly without any issues export type test = { 'fnc1': () => void, 'fnc2': () => void, ...

The element is implicitly assigned to an 'any' type due to the inability to use a 'string' type expression to index the 'Breakpoints' type

I have a question related to TypeScript that I need help with. My objective is to create a custom hook for handling media queries more efficiently. Instead of using useMediaQuery(theme.breakpoints.down('md');, I want to simplify it to: useBreakP ...

Error message indicating that the function 'slice' is not defined for the data variable

I've already searched for solutions to a similar issue, but none of them worked for me. I'm dealing with an object that fetches a list of cities including their names, populations, and states. Here is my HTTP service request: cidadesUrl = 'h ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

Discovering the file system with window.resolveLocalFileSystemURL in Typescript for Ionic 3

After reviewing the documentation found on this link for the File plugin, I came across a paragraph that discusses how to add data to a log file. See the example code below: window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) ...

Could adjusting the 'lib' compiler option to incorporate 'dom' potentially resolve TS error code TS2584?

My preferred development environment is Visual Studio where I write Typescript code. I am facing an issue where I simply want to use the command "document.write" without encountering an error. Unlike my previous PC and VS setup, I am now getting an error ...

The type '{ status: boolean; image: null; price: number; }[]' does not include all the properties required by the 'SelectedCustomImageType' type

While developing my Next.js 14 TypeScript application, I encountered the following error: Error in type checking: Type '{ status: boolean; image: null; price: number; }[]' is missing the properties 'status', 'image', and &apos ...

Error encountered when attempting to utilize ngTemplate to embed filter within a table

I am facing an issue with a component that includes a primeng table. Within a table row, I have an ng-container to project a p-columnFilter into the table from an external source. However, when trying to pass the filter into the template, I encounter a Nul ...

What is the best way to format a string into a specific pattern within an Angular application

In my Angular component, I have 4 fields: customerName, startDate, and startTime. Additionally, I have a fourth field that is a textarea where the user can see the message that will be sent via email or SMS. Within my component, I have defined a string as ...

Issues with slider functionality in a Next.js application styled with Tailwind CSS

"use client"; import React, { useState } from "react"; const textData = [ { id: 1, text: "Text 1 Description", }, { id: 2, text: "Text 2 Description", }, { id: 3, text: "Text 3 ...

React TypeScript - Module not found

Organizational structure: src - components - About.tsx In an attempt to optimize performance, I am experimenting with lazy loading: const About = React.lazy(() => import('components/About')); However, Visual Studio Code is flagging &ap ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

What is the method for retrieving the name of an object's property within an Angular template

I am trying to display the name of a nested object's property using Angular interpolation <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue"> <tr *ngFor="let qtyMap of item.value | keyvalue"&g ...