Components not being updated by Deno signal

My Component

import { h } from 'preact';
import { quoteSignal } from '/quoteStore.ts';

export default function Button() {
  return (
    <button>hello 1 {quoteSignal.value}</button>
  );
}

my signal

import { signal } from '@preact/signals';

// Setting up a signal for the shared label
export const quoteSignal = signal('first');

My island

import { useEffect } from 'preact/hooks';
import { quoteSignal } from '/quoteStore.ts';

export default function QuoteIsland() {
  useEffect(() => {
    quoteSignal.value = "Test Label";
    console.log("useeffect")
    const fetchQuote = async () => {
      const response = await fetch('/api/quote/mystock');
      const data = await response.json();     
      console.log(data.price);
      quoteSignal.value = data.price;
    };

    fetchQuote();
    const intervalId = setInterval(fetchQuote, 10000); // Every 10 seconds

    return () => clearInterval(intervalId);
  }, []);

  return null; // This component doesn't need to render anything
}

The label "Test Label" is not being shown, and neither are any updates from the API, despite them showing in the console log. The button simply always displays its default label of "first".

Answer №1

Greetings from a new maintainer!

If you need to pass a signal between different areas or islands, make sure to use props. Fresh does not support sharing data through globals in other ways.

The reason for this limitation is that Fresh primarily runs components on the server by default. When an island is created, we generate a JavaScript bundle optimized for the browser. This island is then embedded into the bundle during the bundling process. The HTML is rendered on the server and sent to the browser, where the relevant bundles are loaded to instantiate the islands.

Since Fresh focuses on running JavaScript in the browser using its island architecture, signals used in components like Button that are only rendered on the server will not be recognized by the browser. If Fresh was strictly a server-side framework without any browser-side functionality, global signals could be shared successfully.

The strength of Fresh lies in its ability to run JavaScript in the browser for specific parts of the page using islands. If the Button component is never rendered in the browser, no updates will occur regardless of how data is passed to it. The browser interacts with the final HTML generated by the server and creates interactive islands based on that information, without knowing if a Button component contained a signal.

Data sharing between the server and the browser occurs through the props of an island. All props are serialized and sent along with the HTML to the browser. Any data not included in an island's props will not be shared. In the browser, only islands and their referenced components will be interactive, while everything else remains static.

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

Using 'expect', 'toBe', and 'toEqual' in Angular 2 - A step-by-step guide!

Looking to implement something I came across that resembles this: let item1 = {value:5}; let item2 = {value:5}; // Should result in true. expect(item1).toEqual(item2); Unfortunately, an error is being thrown: EXCEPTION: Error in :0:0 caused by: expect ...

Can you explain the distinction between using [ngFor] or [ngForOf] in Angular 2?

From what I gather, both serve the same purpose. However, ngFor operates similar to collections. ngForOf functions more like generics. Am I correct in my understanding? Or can you provide more insight on the differences between ngFor and ngFor ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Revise the React component for a more concise solution

In my code, I am utilizing a REACTJS Office UI Component known as details list available at this link. The goal is to make my application capable of rendering information from any type of SharePoint List regardless of the columns it contains. To achieve th ...

Show text on a button press in Angular

I have set up a group of three buttons using ngFor, each button has its own unique name stored in an array called buttonData[]. The buttonData array also includes corresponding text and images for each button. My goal is to display a specific text and imag ...

Angular 6 custom elements encounter syntax and shadow DOM errors on IE11 and Firefox, causing failures

After following a set of instructions found on this website, I successfully created a new angular-cli project with a custom element that functions perfectly on Chrome. However, when adding the necessary polyfills for Internet Explorer, I encountered an iss ...

How to Pass Data as an Empty Array in Angular 6

After successfully implementing a search function that filters names from an array based on user input, I encountered an issue when trying to make the searchData dynamic by fetching it from a Firebase database: getArray(): void { this.afDatabase.list( ...

What is the best way to preserve an enumeration value in TypeScript?

Is there a way to save enumeration values in TypeScript? For instance: createArticle(name: string, clr: ??enumeration??) { return axios.post(`${environment.apiUrl}/cards`, { card: `${name}`, color: ??clr?? }, ... } PS: Conte ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

I'm struggling to get a specific tutorial to work for my application. Can anyone advise me on how to map a general URL to the HTTP methods of an API endpoint that is written in C

I am struggling to retrieve and display data from a C# Web API using Typescript and Angular. As someone new to Typescript, I followed a tutorial to create a service based on this guide: [https://offering.solutions/blog/articles/2016/02/01/consuming-a-rest- ...

Steps for importing Typescript-exporting libraries in next.js

Encountering a challenge while attempting to import a component from a private library that exports Typescript, we are met with the following error message: Module parse failed: Unexpected token (82:7) You may need an appropriate loader to handle this file ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

Angular is unable to retrieve the /page resource

I attempted to deploy an angular application on Google Cloud, however, I encountered an issue where only the home page was properly deployed. Whenever I tried clicking on any other button in the navigation bar, it resulted in an error message stating "Erro ...

Issue with applying Angular animation to child element

Here I have set up two different animations. animations: [ trigger('fadeIn', [ transition('void => *', [ style({opacity: 0}), animate(500), ]), ]), trigger('fallIn',[ transition ...

How do I connect with the global error handling in Vue?

Within my Vue2 application, I am seeking a method to capture global Vue errors and transmit them to a logging or monitoring service such as Sentry. After attempting to overwrite the global error handler of Vue, I noticed that console logs were no longer a ...

Is there a way to retrieve the setState function from React Context and establish it as the initial value within createContext?

I am currently working with a very basic react context that looks like this: import { FC, createContext, useState, Dispatch, SetStateAction, PropsWithChildren } from "react" export const UserContext = createContext<UserContextType ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

Visual Verification

I'm currently working on a NestJS application that serves images with authentication requirements. I have implemented JWT for authentication, but I encountered an issue when trying to display the image in an img tag because I cannot attach the Authori ...

Error: Unable to perform operation on undefined object when trying to map over 'reminder' object

I've been struggling with my reminder-list.tsx file. No matter how many times I try to fix it, I always end up failing. Can someone help me figure out how to resolve this issue? Every time I run the code, I get the TypeError: undefined is not an obje ...