Exploring the concept of 'Abstract classes' within the Svelte framework

As someone who is relatively new to Svelte and frontend development (with primary experience in Rust/C++/Python), I hope you can forgive me for asking what might seem like a basic question.

My goal is to showcase different kinds of time-indexed data, with a user-editable "timestamp" variable. I aim to exhibit the relevant item from each dataset based on the provided timestamp.

For instance, let's consider temperature and rainfall readings as my datasets:

interface Temperature {
temperature: number
}
interface Rainfall {
rainfall: number
}
A = [{"timestamp" : 0, "temperature": 20}, {"timestamp": 1, "temperature": 25}, {"timestamp" : 2, "temperature": 28}]   
B = [{"timestamp" : 0, "rainfall": 200}, {"timestamp" :1, "rainfall": 210}, {"timestamp": 2, "rainfall": 220}]

I have created Svelte components for Temperature and Rainfall that align with the respective Typescript interfaces. However, I am unsure how to abstract the fact that each data type has a timestamp and a unique way of displaying itself as a Svelte component. In an object-oriented language, I would typically use an abstract class with a display() method to return the appropriate Svelte component.

Is there a method within Svelte or JavaScript to craft universal code that selects the relevant datum from a list based on the timestamp and then showcases it using the corresponding Svelte component?

Thank you for your assistance.

Answer №1

To showcase the data in a component, consider adding a property and displaying it using <svelte:component>. However, if the data is fetched from a server, this approach may not work.

An alternative method would be to use a mapping with a type property. For example:

interface Temperature {
  type: 'temperature';
  temperature: number;
}
interface Rainfall {
  type: 'rainfall';
  rainfall: number;
}

type Datum = Temperature | Rainfall;
<script lang="ts">
  // ...
  import TemperatureComponent from '...';
  import RainfallComponent from '...';

  export let item: Datum;

  const displayMapping: Record<Datum['type'], SvelteComponent> = {
    temperature: TemperatureComponent,
    rainfall: RainfallComponent,
  }
</script>

<svelte:component this={displayMapping[item.type]} {...item} />

Another option is to utilize an {#if}/{:else if} chain based on the type.

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

Cookie setting issue in Next.js/React: The frustration continues

I'm currently attempting to retrieve a cookie in Next.js using Express, but while the backend functions correctly with Postman and retrieves the cookie token, the frontend is unable to obtain the cookie. Below is my backend code: const express = requi ...

Using the default theme in Material UI5

Could someone please explain how to pass in the default theme in Material UI5? In Material UI6, I used to do it like this: const useStyles = makeStyles((theme) => ({ home: { display: "flex", paddingTop: "8rem", width: ...

The Node.js Express undefined callback function is causing issues

I'm currently working on a personal project and I don't have much experience with nodeJS. My goal is to retrieve remote JSON data, generate statistics based on that data, and display it. However, I am encountering some issues with the callback fu ...

Passing data from a child component to a parent component in Vue 3: How

Struggling with Vue 3 app authentication through event-emission from child to parent. Below is a snippet of the code: Child <template> <form class="msform"> <input @click="goToLogin" type="button" name=&q ...

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

Getting permission for geoLocation service on iOS in Ionic: A step-by-step guide

I have recently developed a social media application that utilizes geoLocation services. The app is built with Ionic 4 and has a Firebase backend. While the GeoLocation services are functioning properly on Android devices, users of iOS are not being prompt ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

I am experiencing an issue where localhost is not displaying the JSON output for the Router and controller that I have

Recently delving into the world of NodeJS, I find myself facing a roadblock. While attempting to manage requests, my localhost appears to be endlessly loading or throwing an error. Error: cannot GET/ I aim to showcase the JSON data on my local site. Wh ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

How can I upload an image file using VueJS and Django Rest Framework?

Hello, I am currently in the process of editing a blog page using VueJS and Django Rest Framework. However, I am facing an issue when trying to upload a photo - I keep receiving an error message stating that "the sent data is not a file." Additionally, I a ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

ExtJs encounters missing files in directory - Error: Module '<path>modern-app-3 ode_modules@senchaextpackage.json' not found

I am currently in the process of setting up a new ExtJs project by following the instructions provided here. Upon completing the installation of ext-gen, I proceeded to create a new app using the command ext-gen app -a -t moderndesktop -n ModernApp3, but ...

Securing a JWT token post login

I am new to NodeJS and despite trying numerous solutions, I am facing a challenge. My project involves NodeJS, MongoDB, Express, and Vanilla JS rendered through Pug with an MVC structure. Issue Current Status: I can successfully log in a user and recei ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Using React with Typescript: Anticipating child component with particular props

I'm currently developing a component that necessitates the use of two specific child components. These two components are exported using dot notations from the main component and have defaultProps for identification within the main component: export ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...