What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code:

export function Artist() {
  const params = useParams<{ id: string }>();
  const [data, setData] = createSignal(null);
  createEffect(() => {
    fetchArtist({
      devToken: import.meta.env.VITE_MUSICKIT_TOKEN,
      musicUserToken: MusicKit.getInstance()?.musicUserToken,
      id: params.id,
    }).then((res) => setData(res));
  });

  return (
    <div class={styles.artist}>
      <Show when={data()}>
        <div class={styles.artist__header}>
          <div class={styles.artist__header__image}>
            <img
              loading="lazy"
              decoding="async"
              src={replaceSrc(
                data()?.data[0].attributes?.editorialArtwork?.subscriptionHero
                  ?.url || data()?.data[0].attributes?.artwork?.url,
                data()?.data[0].attributes?.editorialArtwork?.subscriptionHero
                  ?.height || data()?.data[0].attributes?.artwork?.height,
              )}
              alt="Album Art"
              width={100}
              height={100}
              class={styles.artist__header__image__img}
            />
          </div>
          <div class={styles.artist__header__info}>
            <div class={styles.artist__header__info__title}>
              {data()?.data[0].attributes?.name}
            </div>
            <div class={styles.artist__header__info__subtitle}>
              {data()?.data[0].attributes?.genreNames?.[0]}
            </div>
            <div class={styles.artist__header__info__actions}>
              <ButtonPrimary
                label="Play"
                icon={IoPlay}
                onClick={() => {
                  setIsShuffle({ value: 0 });
                  setQueue("artist", data()?.data[0].id, true);
                }}
              />
            </div>
          </div>
        </div>
        <div class={styles.artist__body}>
          <ArtistViewSelector artist={data} data={data} />
        </div>
      </Show>
    </div>
  );
}

I am encountering an issue where the ArtistViewSelector component does not update when the fetched data changes. This becomes apparent when I navigate to a different artist on the same page.

It seems that only the elements outside the ArtistViewSelector are being updated while the rest remains static. I am currently investigating the root cause of this behavior.

Answer №1

Without knowing the inner workings of ArtistViewSelector, it's impossible to determine the best course of action, but there are a number of issues present in your component.

It is crucial to avoid using an effect to update state, as this can lead to an endless loop within your component.

Rather than placing fetchArtist inside an effect, consider integrating it directly into the component itself. The fetch request will still be triggered since components inherently come wrapped in effects internally.

Lack of error handling is another concern. Not all fetch requests may successfully resolve to a value, so incorporating error handling is essential.

While there are additional issues at play, for brevity, I'll refrain from delving further.

The optimal approach involves utilizing a resource for data fetching and rendering. The Resource API permits the transmission of fetch requests with query parameters, managing re-fetches and errors through clean, concise code.

This can also be achieved utilizing the fetch API. Refer to this answer for guidance on implementing both methods:

For information on the Resource API, visit:

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

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

Can you explain the meaning of <T = {}>?

While browsing through the documentation, I came across this generic type: type GConstructor<T = {}> = new (...args: any[]) => T; https://www.typescriptlang.org/docs/handbook/mixins.html Above this line, there is a brief mention that it is a Gene ...

Error encountered numerous times within computed signals (angular)

I have incorporated signals into my Angular application. One of the signals I am using is a computed signal, in which I deliberately introduce an exception to see how it is handled. Please note that my actual code is more intricate than this example. pu ...

Receiving an error in Typescript when passing an object dynamically to a React component

Encountering a typescript error while attempting to pass dynamic values to a React component: Error message: Property 'title' does not exist on type 'string'.ts(2339) import { useTranslation } from "react-i18next"; import ...

TS2365: The '!== 'operator is not compatible with the types ""("" and "")""

function myFunction(identifier: string) { identifier = "("; }; let identifier: string = ")"; if (identifier !== '(') throw "Expected '(' in function"; myFunction(identifier); if (identifier !== ')') throw "Expected &a ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

Create a d.ts file in JavaScript that includes a default function and a named export

While working on writing a d.ts file for worker-farm (https://github.com/rvagg/node-worker-farm), I encountered an issue. The way worker-farm handles module.exports is as follows: module.exports = farm module.exports.end = end When trying to replica ...

Nestjs: Can't find property in Mongoose document

I am currently encountering some issues with the following code while using Nestjs along with Mongoose: import { Injectable } from '@nestjs/common'; import { Key, KeyDocument } from '@app/mongo'; import { Model } from 'mongoose&apo ...

Error notifications continue to appear despite the presence of data in the input field

I am utilizing a component to exhibit various information (such as first name, last name, phone number, etc.) fetched from the API. The main focus is on executing CRUD operations, particularly the update operation. Referencing the image below: An is ...

NextJS: Error - Unable to locate module 'fs'

Attempting to load Markdown files stored in the /legal directory, I am utilizing this code. Since loading these files requires server-side processing, I have implemented getStaticProps. Based on my research, this is where I should be able to utilize fs. Ho ...

Removing empty options from a select dropdown in Angular 9

In the process of working with Angular 9, I am currently in the process of constructing a dropdown menu that contains various options. However, I have encountered an issue where there is a blank option displayed when the page initially loads. How can I eli ...

When using TypeScript, a typed interface will not permit a value that is not within its specified string literal type

I have downsized my issue to a smaller scale. This class needs to set the default value of its "status" property. The type T extends the string literal type "PossibleStatus" which consists of 3 possible strings. Typescript is giving me trouble with this. ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

I'm facing difficulty in assigning props because of the specific nature of generics in Typescript

My goal is to create a Higher Order Component (HOC) that can control a component which relies on certain props to function properly. To elaborate: I want to build a HOC that takes a component expecting props value and onChange, and modifies it so that the ...

Issue encountered: Jest-dom is throwing a TypeError because $toString is not recognized as a function on a project using Typescript, React

I have been facing a challenge while setting up jest and @testing-library/jest-dom for my typescript/react/next.js website. Each time I try running the tests, an error occurs, and I am struggling to identify the root cause. This issue has been perplexing ...

Tips for utilizing an elective conversion by typing

In my opinion, utilizing code is the most effective approach to articulate my intentions: interface Input { in: string } interface Output { out: string } function doStuff(input: Input): Output { return { out: input.in }; } function f<Out>(input ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Angular TimeTracker for tracking time spent on tasks

I need help creating a timer that starts counting from 0. Unfortunately, when I click the button to start the timer, it doesn't count properly. Can anyone assist me in figuring out why? How can I format this timer to display hours:minutes:seconds li ...