What could be causing the lack of reflection in the UI for the signal update?

Recently, I have been working on some code in SolidJS.

Specifically, I am utilizing createSignal to handle the rendering of certain views based on changes within the options array.

import { render } from "solid-js/web";
import { createSignal, Show, Index } from "solid-js";

const optionsList = [
        {
            title: "ReactJs",
            subtitle: "A front-end framework for building views on the web",
            selected: false
        },
        {
            title: "SolidJS",
            subtitle: "Lorem, ipsum dolor sit amet consectetur adipisicing.",
            selected: false
        },
        {
            title: "MumboJumboJS",
            subtitle: "null",
            selected: false
        }
    ]

export default function CheckboxArea(props) {
    const [options, setOptions] = createSignal(props.options);
    console.log(options())

    function handleOnClick(index: number) {
        console.log("Click")
        const op = options()
        op[index].selected = true
        setOptions(op)
    }

    return(
        <div>
            <Index each={options()}>{(each_option, index) =>
                <div onClick={() => handleOnClick(index)}>
                    <Show when={options()[index].selected}>
                        <div>{each_option().title}</div>
                    </Show>
                    <Show when={!options()[index].selected}>
                        <div>{each_option().subtitle}</div>
                    </Show>
                </div>
            }
            </Index>
        </div>
    )
}

render(() => <CheckboxArea options={optionsList}/>, document.getElementById("app")!);

Despite registering click events and updating through options(), the views fail to update accordingly.

Answer №1

When attempting to modify an existing value and assign it as the new value, keep in mind that signals internally run equality checks. Since you are passing the same value back, and arrays are objects compared by reference, the signal's value will not be updated.

There are various solutions available, with the simplest being to create a new array with the updated values and set it as the new value:

function updateList(index: number) {
  setOptions([...updatedList]);
}

Another option is to set equals to false on the signal to enforce an update even if the value remains the same:

createSignal(props.options, { equals: false });

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

Alert for every URL modification

Is it feasible to receive (event) notifications for every URL change (without refreshing the page, as possible with location.replaceState())? To clarify: I am not altering components or pages, just updating the URL for future reference. UPDATE Potential ...

Steps to configure Visual Studio Code to automatically open the original TypeScript file located in the "src" folder when a breakpoint is hit in a Node.js application

I am currently working on a CLI node application and using VSCode to debug it. Everything seems to be working fine, except for one annoyance: when I hit a breakpoint, VSCode opens the source map file instead of the actual TypeScript file located in my "src ...

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Utilizing Typescript to retrieve a specific object property using square brackets and a variable

How can we correctly access a JavaScript object in TypeScript using variable evaluation with bracket notation, such as myObject[myVariable], when the value of the variable is unknown initially? In the code below, an error occurs due to the uncertainty of ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

An offbeat symbol discovered when using conditional rendering

I encountered an unexpected token error while working on conditional rendering. Even though everything seems to be correct, I can't seem to pinpoint the issue. {isAdd===true? countries.map(item=>{ return( <Men ...

Reconstructing the complete pathway using object identifiers

Imagine I have a set of website routes represented by the object below: const routes = { HOME: "start", ACCOUNT: { HOME: "account", PROFILE: "profile", ADDRESSES: { HOME: "addresses", DETA ...

Modifying text on input buttons using Javascript

Including product names, text forms, and buttons on a webpage is essential for showcasing products effectively. Each product is assigned an ID such as p1, p2, etc., while the input types are identified by i1, i2, etc. When users enter information into the ...

Tips for resolving the issue of missing metadata for open graph and Twitter cards in a Next.js project

Having trouble with error messages while running the build version in Next.js. I've added meta tags to the layout, but the issue persists. As a newcomer to Next.js, I'm looking for guidance on how to fix this problem. Any help or advice on troubl ...

Discover the most frequently repeated elements in a JavaScript array

I'm working with an array that contains multiple names such as: [mike, bob, john, john, rick, bob] Could anyone advise on the most efficient method to determine which name appears the most frequently? ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says Uncaught TypeError: L.GeometryField is not a constructor. My code involves AJAX calls. <script> var csrftoke ...

Generate an li element that is interactive, containing both text and a span element

I am dealing with a JSON array that looks like this: var teamDetails=[ { "pType" : "Search Engines", "count" : 5}, { "pType" : "Content Server", "count" : 1}, { "pType" : "Search Engines", "count" : 1}, { "pType" : "Business", "count" : 1,}, { "pTyp ...

Can you explain the variance between the two state updates in React?

Currently enrolled in a React course where the instructor is diving into state updates. I'm struggling to grasp the internal differences between these two code snippets, provided below for reference: Snippet that updates state directly class Counter ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...