Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an issue with updating the url parameters via a div on:click event; although the API is being called and returns data, the PageData object does not update as expected.

Below is my implementation of the onClick:

import { goto } from '$app/navigation'; 
const adhigaramClick = (adhigaram: string) => {
        selectedAdhigaram = adhigaram
        $page.url.searchParams.set('adhigaram',adhigaram); 
        goto(`?${$page.url.searchParams.toString()}`);
    }

Here is the corresponding API call in the +page.server.ts file:

export const load: PageServerLoad = async ({url, params}) => {
    let selectedPaal = "test";

    const paramPaal = url.searchParams.get("paal");
    const adhigaram = url.searchParams.get("adhigaram");

        if (paramPaal) {
            selectedPaal = paramPaal;
        }
        
    const response = await api('GET', `page/${selectedPaal}${adhigaram ? `/${adhigaram}` : ''}`);
    
    if (response.status === 404) {
        return {
            data: {} as Page
        };
    }

    if (response.status === 200) {  
        return {
            ... (await response.json()) as Data
        };
    }
    throw error(response.status);
};

I also utilize the +page.svelte.ts file to access the response data (PageData):

import type { PageData } from './$types';

    export let data: PageData;
    $: console.log(data);

Lastly, clicking on the a tag triggers page re-rendering successfully:

<a href={`?paal=${paal.keyword}`} >
    {paal.titleTamil}
</a>

Answer №1

Invalidation might be the solution you are seeking.

SvelteKit keeps track of dependencies in each load function to avoid unnecessary re-running during navigation. For instance, a load function in a main +layout.js doesn't need to re-run when switching from one page to another unless it references url or a member of params that has changed since the last navigation.

A load function will trigger a re-run under the following circumstances:

  • It refers to a property of params whose value has been altered
  • It refers to a property of url (such as url.pathname or url.search) whose value has changed
  • It includes await parent() and a parent load function was re-executed
  • It specified a dependency on a specific URL through fetch or depends, and that URL was deemed invalid with invalidate(url)
  • All active load functions were forcibly re-run using invalidate()

If a load function is set off for a re-run, the page will not reload — instead, it will refresh with the updated data. As a result, components' internal state remains intact. If this is not what you desire, you have the option to reset anything required inside an afterNavigate callback, and/or enclose your component in a {#key ...} block.

Answer №2

Expanding upon the response from @FlippingBinary, I encountered an issue where the load function was not being rerun, resulting in a lack of UI updates.

Implementing the {#key ...} block resolved the re-rendering issue for me.

Link to further details on Svelte template syntax key usage

J

Answer №3

If you're facing challenges with data updates in slot content of components, try this workaround:

<script>
...
$: data, data = data
...
</script>

By using this approach, you can prompt re-rendering when the data changes, keeping the component informed of any updates without resorting to a resource-intensive call like invalidateAll().

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

The file or directory npx-cli.js cannot be found in the specified location: ../npm/bin/

Problem Description After creating a new React project using the command below, npx create-react-app my-app --template typescript and utilizing node version v18.15.0, I attempted to set up Prettier for the project following the instructions in the Pretti ...

Balancing website speed with capturing product impression

I've been tasked with capturing impressions of all the products visible in the viewport on a website that features thousands of products. To achieve this, I implemented a directory and utilized the IntersectionObserver, which was referenced within the ...

What methods are recommended for implementing changes in a TypeScript library throughout the development process?

When working on a TypeScript library that is utilized as a dependency by other libraries or applications, how can I efficiently handle frequent updates without going through the process of incrementing the version number, publishing it to an NPM registry, ...

Utilizing Radio buttons to establish default values - a step-by-step guide

I am utilizing a Map to store the current state of my component. This component consists of three groups, each containing radio buttons. To initialize default values, I have created an array: const defaultOptions = [ { label: "Mark", value: & ...

Converting a string to an HTML object in Angular using Typescript and assigning it to a variable

I am facing an issue with passing HTML content from a service to a div element. I have a function that fetches HTML content as a string from a file and converts it into an HTML object, which I can see working in the console. However, when trying to assign ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

Running complex Firestore query within Cloud Functions

Currently, I am developing triggers that interact with a Firestore movie and user database. The main goal of one trigger is to present a new user with a list of top-rated movies in genres they have selected as their favorites. To achieve this, I store the ...

What are the steps to customize the collapse and expand icons?

Having trouble changing the icon up and down when collapsing and expanding with the code below. <div class="attach-link"> <a href="javascript:void(0);" *ngIf="fileData.fileDataType.canAttach && !isFinancialEntity" (click) ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Expanding Material UI functionality across various packages within a monorepository

Currently, I am using lerna to develop multiple UI packages. In my project, I am enhancing @material-ui/styles within package a by incorporating additional palette and typography definitions. Although I have successfully integrated the new types in packag ...

Issue with IN operator functionality in TypeORM when used with MongoDB

My goal is to fetch a list of items using an array of IDs by utilizing the following code: import { In } from 'typeorm'; ...findBy({ _id: In(ids) }) The IDs are predefined upon creation: @Entity() export class Foo { @ObjectIdColumn({ generated ...

Error in Angular 2 component when loading background images using relative URLs from an external CSS skin

In my angular2 component, I am utilizing a third-party JavaScript library. The skin CSS of the component attempts to load images using relative URL paths. Since I am following a component-based architecture, I prefer to have all component dependencies enca ...

Attempting to create a sorting functionality using Vue and Typescript

I am trying to implement a feature where clicking on the TableHead should toggle between sorting by most stock on top and least stock on top. Currently, I have two buttons for this functionality, but it's not very user-friendly. My approach involves ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Is it feasible to conditionally set a function parameter as optional?

type TestType<A> = [A] extends [never] ? void : A class Singleton<T, A> { private ClassRef: (new (...args: A[]) => T) private args: TestType<A> private _instance?: T constructor(ClassRef: (new (...args: A[]) => T), ...

Instructions for implementing personalized horizontal and vertical scrolling within Angular 9

I am currently working on an angular application where users can upload files, and I display the contents of the file on the user interface. These files may be quite long, so I would need vertical scrolling to navigate through them easily. Additionally, fo ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

What is the best way to utilize a reduce function to eliminate the need for looping through an object in JavaScript?

Currently, my code looks like this: const weekdays = eachDay.map((day) => format(day, 'EEE')); let ret = { Su: '', Mo: '', Tu: '', We: '', Th: '', Fr: '', Sa: '' }; w ...

What distinguishes the ///<reference path="..."/> from an import statement?

Initially, when I try to import React in my code, the TypeScript compiler displays an error saying 'can not find module react'. However, after adding /// before the import statement, the problem is resolved. Interestingly, I later discovered tha ...