Sveltekit - dynamic loader wheel for various loading sources with automatic retry feature

I want to create a simple spinner for my SvelteKit pages, but I'm unsure of the best approach. The goal is to display a loading spinner when the page loads a maplibre map. If the loading process fails, I need it to retry after 5 seconds. Even after the map is loaded, I still need to show the spinner as additional data is fetched. Again, if the request fails, it should keep retrying until successful. The spinner should only hide once everything has been successfully loaded.

Here's a snippet of the code:

onMount(() => {
    let map = new Map({}); //maplibre map
    map.on('load', function(){
        let data = fetch('url').catch((e)=>{
            //retry additional load in 5 sec.
        });
    });
    map.on('error', function(){
       //retry map load in 5 sec.
    });
});

The retry logic adds complexity as I have to handle keeping references to each loading function and calling them again. Are there any best practices or established solutions for this kind of scenario?

Answer №1

Uncertain of the optimal approach, but my recommendation would be:

  • Ensure that each retryable task is encapsulated within its own Promise
  • Consider utilizing a resiliency library, such as cockatiel
  • Incorporate the resiliency library to sequentially execute promises within onMount()

For your specific scenario, the implementation might resemble the following:

import { retry, handleAll, ConstantBackoff } from 'cockatiel';
import { onDestroy, onMount } from 'svelte';

const retryPolicy = retry(handleAll, { maxAttempts: 2, backoff: new ConstantBackoff(50) });

let map;
function loadMap() {
    map = new Map({});
    const promise = new Promise((resolve, reject) => {
        map.on('load', function () { resolve(); });
        map.on('error', function () { reject(); });
    });
    return promise;
}

const abortController = new AbortController();

onMount(async () => {
    try {
        await retryPolicy.execute(() => loadMap(), abortController.signal);
        let data = await retryPolicy.execute(() => fetch('url'), abortController.signal);
    } catch {
        if (abortController.signal.aborted) return;
        // TODO: Handle case where all retries failed
    }
});

onDestroy(() => {
    abortController.abort(); // Will stop the retries
});

If async/await isn't preferred, you have the option to rewrite using .then() and .catch().

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

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...

RequireJS has an unbreakable reliance on the library

For my Angular + Require project, I encountered an issue while trying to package the application with r.js using: node r.js -o app.build.config.js Despite everything working fine, the library files were not found on the specified path. Instead, the depen ...

Retrieving data from a SQL database using Node.js

As a newcomer to Node.js, I managed to fetch SQL results from my database using the code snippet below: var express = require("express"); var app = express(); var mysql = require('mysql'); app.get("/",function(req,res){ var client = mysql.c ...

Sending multiple form fields using Ajax and the form ID to make a single submit call to the specified URL

<form id="adultval" class=""> <input id="txtFirstName" type="text" name="First Name" placeholder="First Name" class="form-control" minlength="2" required> <input id="txtLastName" type="text" name="Last Name" placeholder="Last Name" ...

Transfer data to the local context of JavaScript functions

My usual approach involves using a structure similar to this: var $this, url, callback; //private variables loadCallback = function($that, url, callback) { return function(responseText, textStatus, req) { ... }; })($this, url, callback) H ...

Getting a specific element of the "Event" object using javascript/typescript

Overview I successfully integrated a select box into my Vue.js/Nuxt.js application using Vuetify.js. I utilized the @change event to capture the selected value. <v-select v-model="selectedStartTime" :items="startTime" item ...

Switch back emulation when moving away from page - using angular javascript

I have a unique scenario in my component.ts file on a specific page where I need to incorporate custom CSS for printing purposes: @Component({ selector: "dashboard", templateUrl: "./dashboard.component.html", styleUrls: ["./d ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Steps for resolving the problem: [$sce:itype] while using AngularJS version 1.6

I'm encountering an issue with $sce while using AngularJS 1.6.4: Error: [$sce:itype] http://errors.angularjs.org/1.6.4/$sce/itype?p0=html Stack trace : L/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425 trustA ...

Ways to integrate data produced from two distinct functions into a third function

I have two data sets that were generated by separate functions and are of different types. These datasets cannot be combined (concatenated, joined, etc.). I want to use both datasets in a third function as shown below. How can I achieve this? function a ...

There was an issue encountered while working with Node.js: Unable to load resource - the server returned a 404 error (Not Found)

Hello everyone, I hope you're all well. I have a question regarding creating a navigation bar and serving it on my server. Every time I try to do so, I am getting a 404 not found error. However, I have placed my logo file in the same directory as my H ...

Utilizing the power of Vue Router with DataTables

I am currently facing an issue where I want to include links or buttons in my DataTable rows that can navigate to a vue route when clicked. The straightforward approach would be to add a normal <a> element with the href attribute set to "/item/$ ...

The navigation links in my React project are not appearing on the screen as expected

Hello everyone, I am relatively new to React and recently I have been attempting to utilize `react-router` in order to construct a Single Page Application. My goal is to link all the pages (such as Home, About, Login, etc) in the navigation bar using the & ...

Date discrepancy detected on AWS EBS server; however, it is operating seamlessly on the local environment

Whenever deployed on an AWS server, there seems to be a recurring miscalculation. Background: All dates stored in my MongoDB are in UTC format. I need them converted to IST before exporting them to Excel. While my code functions flawlessly on my local m ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Looking for assistance with PHP and JavaScript integration

I am struggling with an update-like function that I need help with: <html> $result = mysql_query("SELECT *FROM tbl_a LEFT JOIN tbl_b lass ON tbl_b.b_id=a.class_id LEFT JOIN category ON category.category_id=tbl_a.category_id WHERE list ='{$id}&a ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

Adjust the alignment of radio buttons in an HTML form based on the orientation of the device

As a newcomer to HTML and jQuery, I am currently working on an html form that will be used across multiple tablets. My goal is to have the available options displayed in two rows when the tablet is in portrait mode, like this: However, when the tablet is ...

Refreshing chord chart information from a JSON source in d3.js

I have two functions that are responsible for creating and drawing a D3 chord diagram representing the netflow between different IP addresses in our network. Function 1 (for creating the chord diagram) function createChords(jsonURL, containerID, tooltipI ...

Determine whether a child node is an element or a text node using JavaScript

I am experiencing an issue with the childNodes property. Here is the scenario: <ol> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ol> //childNodes.length = 7 However, <ol><li> ...