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

How can I access other properties of the createMuiTheme function within the theme.ts file in Material UI?

When including a theme in the filename.style.ts file like this: import theme from 'common/theme'; I can access various properties, such as: theme.breakpoints.down('md') I am attempting to reference the same property within the theme ...

Enhancing your TypeScript version

Whenever I try to update my global version of TypeScript by running npm install -g typescript, the Angular project still shows an older version when I run ng v. Why does this happen and how can I ensure a consistent upgrade? https://i.stack.imgur.com/JzwK ...

Methods to close the currently active ngx-modal when a new modal is triggered within the same Angular 8 component

I am currently working on developing a versatile modal component that has the ability to be called from within the same modal itself. Is there any way to configure the component and modal in such a manner that when the reusable component is triggered, it ...

The sequence of operations when assigning in Typescript with || and utilizing the array .find method

I need to ensure that the operations in my assignment are happening in a specific sequence. As far as I can tell, it should be following the order listed below. However, I have not been able to locate any documentation on TypeScript that definitively confi ...

Tips for changing a created Word file with Docxtemplater into a PDF format

Hey there! I am currently in the process of building a website with Angular.js and have successfully managed to generate a word document from user input. Everything was working fine until I encountered an issue. I now need to provide a way for users to pr ...

Enhanced string key indexer type safety in TypeScript

Discover and explore this online TypeScript playground where code magic happens: export enum KeyCode { Alt = 'meta', Command = 'command', // etc. } export type KeyStroke = KeyCode | string; export interface Combination { comb ...

Tips for passing a query parameter in a POST request using React.js

I am new to working with ReactJS and I have a question about passing boolean values in the URL as query parameters. Specifically, how can I include a boolean value like in a POST API call? The endpoint for the post call is API_SAMPLE: "/sample", Here is ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

What is the best way to retrieve class members using component properties?

I am looking to implement a mixin for setting the header and meta data in my project. I recently discovered vue-meta, which seems to work really well for this purpose. However, I am still getting acquainted with TypeScript and class-based components. How ...

Converting an array of objects into a TypeScript dictionary with IDs as the key mapping

Is there a way to provide type hints for better autocompletion when accessing keys like dictionary.Germany from the following data and types? type Entry = { tld: string; name: string; population: number; }; const data: Entry[] = [ {tld: 'de&a ...

Utilizing a directive in contexts beyond a component

I have developed a popover module that consists of two components and three directives. However, I am encountering an issue where I am unable to utilize the directives outside of the main component. Whenever I try to do so, I face an editor error stating: ...

Using custom types for prop passing in Next.js with TypeScript

After making a http call, I obtain an array containing JSON data. This data is then assigned to a type called Service. type Service = { id?: string; name?: string; description?: string; }; The api call is made in getServerSideProps and the Service type is ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

What is the reason behind TypeScript's lack of inference for function parameter types when they are passed to a typed function?

Check out the code snippets below: function functionA(x: string, y: number, z: SpecialType): void { } const functionWrapper: (x, y, z) => functionA(x, y, z); The parameters of functionWrapper are currently assigned the type any. Is there a way we can ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

"Exploring the best way to open a new tab in Angular from a component

I am working on a simple Angular application with two components. My goal is to open one component in a new tab without moving any buttons between the components. Here is an overview of my application setup: Within my AppComponent.html file, there is a b ...

In TypeScript Next.js 14 APP, object literals are limited to declaring existing properties

I encountered an error in my typescript next.js 14 APP. I need assistance resolving this issue, which states: Object literal may only specify known properties, and 'productPackages' does not exist in type '(Without<ProductCreateInput, Pr ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

What is the best way to have an icon appear when a child component div is clicked, without it displaying on other similar divs?

Within my child component div, I have configured it to display information from an object located in the parent component. Initially, when the web app loads, it correctly shows three divs with names and messages retrieved from the created object. However, ...

Nestjs: Accessing the request or context using a Decorator

In my current project using NestJS, I am attempting to make the executionContext accessible in a logger for the purpose of filtering logs by request. Each injectable has its own instance of a logger, and I want to maintain this setup (where the scope of t ...