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

conditional operator that compares values in router events

As I examine an object, links = { link1: 'page1', link2: 'page2', link3: 'page3', link4: 'page4', link5: 'page5', link6: 'page6' } I possess a function for retrieving t ...

In TypeScript, is it possible to indicate that a function will explicitly define a variable?

In TypeScript, I am working on creating a class that delays the computation of its information until it is first requested, and then caches it for future use. The basic logic can be summarized as follows. let foo: string | undefined = undefined; function d ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Converting a file into a string using Angular and TypeScript (byte by byte)

I am looking to upload a file and send it as type $byte to the endpoint using the POST method My approach involves converting the file to base64, and then from there to byte. I couldn't find a direct way to convert it to byte, so my reasoning may be ...

The process of linking a Json response to a table

In my products.components.ts class, I am retrieving Json data into the variable this.Getdata. ngOnInit() { this._service.getProducts(this.baseUrl) .subscribe(data => { this.Getdata=data this.products=data alert(JSON.stringify(this.Getdata)); ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Exploring the Method of Utilizing JSON Attribute in typeScript

How to access JSON attributes in TypeScript while working on an Angular Project? I'm currently in the process of building an Angular project and I need to know how to access JSON attributes within TypeScript. test:string; response:any; w ...

The requirement of the second parameter being optional or required will depend on the value of the first

Is there a way to make the second parameter of my function optional or required based on the value of the first parameter? Here's an example code snippet: enum Endpoint { USERS = '/users/:userId', ORDERS = '/orders' } typ ...

Ionic 2 encountering issue with `ctorParameters.map` not being a function error

Recently, I wanted to incorporate the Network-information plugin into my project but encountered compatibility issues with an older version of Ionic-native. To resolve this, I took the following steps: npm rm --save ionic native npm install --save ionic-n ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

Encountering a TS(2322) Error while Implementing Observables in Angular 12

Exploring the intricacies of Angular 12 framework, I find myself encountering a hurdle in my learning journey. The tutorial I am following utilizes the Observable class to query fixed data asynchronously. However, an unexpected ts(2322) error has surfaced ...

Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition: function myFunc( id: string, optionalParamOne?: number, optionalParamTwo?: string ) { console.log(optionalParamTwo); } If I want to call this function and only provide the id and optionalParamTwo, without need ...

Turf.js - Missing type declarations when importing into a Vue/Vite environment

Struggling with Turf.js's bbox functionality. Despite all my efforts, TypeScript type definitions remain elusive. I attempted the following steps: Included in package.json: "dependencies": { ... "@turf/turf": "6.5.0&q ...

Issue with `rxjs/Subject.d.ts`: The class `Subject<T>` is incorrectly extending the base class `Observable<T>`

I found a sample template code in this helpful tutorial and followed these two steps to get started - npm install // everything went smoothly, created node_modules folder with all dependencies npm start // encountered an error as shown below- node_mo ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

Obtain the outcome of HTML5 FileReader by utilizing promises within an asynchronous function

I am encountering a challenge in my Angular 4 application where I am working with an image. I am trying to pass the base64 string to another variable, but due to the asynchronous nature of this process, the image.src ends up being empty. As a result, the ...

Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col] Argument of type 'T[keyof T]' i ...