Is there a way for me to insert a hook into the DOM after a promise has finished updating

Currently, I am tasked with maintaining a code snippet that resembles the following structure:

{#await details}
    {#each values as value, i}
        <td id="{`${config.id}_${i}`}">{value}</td>
    {/each}
{:then details_result}
    {#each details_result as detail, i}
        <td id="{`${config.id}_${i}`}" class:detail="{detail.class}">{detail.value}</td>
    {/each}
{/await}

The challenge at hand involves binding events to these <td> elements using jQuery (specifically bootstrap popovers). However, I am encountering difficulties determining when exactly to perform this event binding due to Svelte's removal and replacement of the <td> elements within the #await block upon executing the :then clause.


Initially, my attempts involved employing Svelte's afterUpdate function for event binding. Regrettably, this proved ineffective as the function executes only after the placement of <td> elements within the #await block, failing to trigger for :then instances.

afterUpdate(() => {
    values.forEach((value, i) => { $(`#${config.id}_${i}`).popover(); });
})

I next explored binding events within the then() onFulfilled function of the details promise. Despite ensuring that event binding occurs post-promise resolution, Svelte fails to update the DOM with the new <td> elements, consequently retaining bindings to the old elements.

$: details = (...) => {
    [...]
    return new Promise(...).then(() => {
        values.forEach((value, i) => { $(`#${config.id}_${i}`).popover(); });
        [...]
    });
}();

How can one implement a callback or hook triggered after Svelte inserts the <td> elements from the :then block? Alternatively, is there a method to compel Svelte to retain references to the <td> HTML elements?

Answer №1

To access references to the DOM elements, you can utilize the bind:this directive. However, managing created and destroyed elements as the list changes can become cumbersome.

Instead, consider using an action for your requirement. This will allow you to attach a custom function to the lifecycle of DOM elements. The function will be executed when an element is created, and you can also include a cleanup function that will be called when the element is destroyed.

An example implementation would resemble the following:

<script>
  export let items = []

  const openPopover = el => { ... }

  // defining the action function
  const popover = el => {

    // perform operations with the DOM element
    el.addEventListener('click', openPopover)

    const destroy = () => {
      // handle cleanup if necessary
      el.removeEventListener('click', openPopover)
    }

    return { destroy }
  }
</script>

{#each item of items}
  <!-- our function will be invoked for every td element -->
  <td use:popover>
    {item.name}
  </td>
{/each}

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

I encountered an issue with my shopping cart while using ReactJS

this is the App.js file import React from "react"; import ListProduct from "./listProduct"; import ListOrder from "./listOrder"; import pizza from "./pizza.jpg"; import './style.css' import { Container,Row,Col,Button } from 'react-boo ...

Locate the highest and lowest values within a .json file

When working on a graph using d3.js, one key step is setting up the scales for the axis. The data for the graph is stored in a Json file with multiple arrays, each representing different regions and years: [{ "id" : "AustraliaNewZealand" , "year" ...

Tips for effectively managing errors in Next.js getStaticProps

Currently, I am immersed in the development of my inaugural Next.JS application (Next and Strapi). All functionalities are operational, but I am interested in discovering the optimal approach to integrate error handling within getStaticProps. I have exper ...

Choose the option for overseeing safaris

Hello there! I need some help with Safari. Can you please guide me on how to disable the arrows? https://i.stack.imgur.com/1gzat.png ...

The lower text box on the page being covered by the virtual keyboard on IOS

Our website features a fixed header and footer with scrollable content. We have 20 text boxes on the page, but the ones at the bottom, like Zip and Telephone, are obscured by the iOS virtual keyboard that appears when a text box is clicked. If we could d ...

Transferring data between Javascript and PHP with AJAX and JQuery

I'm currently working on a basic web page that involves sending data from an HTML page to a PHP script and receiving some data back. My approach involves using AJAX, but for some reason, the PHP script doesn't seem to execute at all. Here's ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

Anticipate that the typescript tsc will generate an error, yet no error was encountered

While working in the IDE to edit the TypeScript code, an issue was noticed in checkApp.ts with the following warning: Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams. Surprisingly, when running tsc, no error ...

React-spring is causing an increase in the number of hooks rendered compared to the previous render in React

I've encountered a similar issue as discussed on SO, but I'm struggling to resolve the problem detailed below. The scenario This code snippet found at the following link is functional: https://codesandbox.io/s/frosty-water-118xp?file=/src/App. ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

Is the AngularJS `$http` cache capable of storing server errors in its cache?

When working with Angular, using $http.get(url, {cache:true}) will cache server responses for easy access. But what happens when the GET request to the server fails? This could be due to a temporary connection issue or a server response such as a timeout. ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Alert box in Vue.js

Embarking on my journey with VueJS. I previously implemented an alert box using jQuery. Now, I am attempting to recreate that in VueJS. Here is my current progress: 1- Developed a component named NovinAlert.vue which includes: <template> & ...

Creating a soft focus effect in a specific region (behind the text)

While working on my homepage created with HTML/CSS/Javascript, I have text positioned at the top left corner of the screen. The challenge arises from the fact that I am using different backgrounds sourced from Reddit, and a script randomly selects one duri ...

Step-by-step guide to uploading files using cucumber-js

Is there a way to write a script that can successfully fill out a form and upload a file using cucumber-js, selenium, and protractor? I am encountering an issue where there is no xpath/id available to click on when trying to upload a file. How have you d ...

Can you provide a database of words for different cities, towns, and countries in MongoDB (or in JSON

Currently, I am in the process of developing an application that utilizes MongoDB. One specific feature I am working on implementing is an 'auto-suggest' functionality on the front-end. For example, as a user begins to type the first few letters ...

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...

What is the best way to extract raw data from a kendo dataSource?

After fetching data for my Kendo grid from the backend and populating it in the alignedProcessesToRiskGridOptions, I noticed that while the data is displayed in the grid, I also need access to the raw data for additional logic. Is there a way to retrieve d ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

What could possibly be the reason for this not returning null?

Consider this JavaScript snippet: var value = parseInt(""); console.log(value != Number.NaN ? value : null); Why does the console output Nan instead of null? Is there a way to modify the code so that it actually returns a null value? I attempted to wra ...