Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How do I access state from +layout.svelte inside +layout.ts or conditionally load data inside +layout.ts

$
0
0
  • New to svelte and sveltekit so please bear with me
  • I have a master detail layout in sveltekit (list of items and detail shown side by side on desktop and shown separately on mobile)
  • The main challenge is that the urls change when filter or search is changed and item is clicked
  • The list has infinite scrolling that keeps adding more and more items as we go down
  • When I click on an item from page 1 it works but clicking on an item from any other page breaks the app

The Problem

When I click on an item from page 1 it works

  • Similarly typing the URL of any item in the address bar directly works

Typing the url of an item from page 1 works

  • But typing the URL of any item in the address bar from page 2 breaks the app

Typing the url of an item from page 2 breaks

URL Structure

src└── routes└── (news)└── [[news=newsMatcher]]├── [[tag]]├──+layout.server.ts├──+layout.svelte├──+layout.ts└──+page.svelte└── [id=idMatcher]└── [title]└──+page.svelte

CodeSandbox Link

+layout.ts

export const load: LayoutLoad = ({ data, fetch, params, url }): LayoutLoadReturnType => {    const filter = (url.searchParams.get('filter') as NewsFilter) || 'latest';    const id = params.id;    const search = url.searchParams.get('search') || '';    const title = params.title;    const {        mapNameNoSpecialCharsToSymbolName,        mapSymbolNoSpecialCharsToSymbolName,        symbolNames,        symbolRanks    } = data;    const endpoint = getNewsListFirstPageEndpoint(filter, search);    return {        filter,        id,        latestNewsPromise: fetch(endpoint).then((r) => r.json()),        mapNameNoSpecialCharsToSymbolName,        mapSymbolNoSpecialCharsToSymbolName,        search,        symbolNames,        symbolRanks,        title    };};
  • This is the file I believe that may have some issue
  • It loads fresh data for every request and this load function is called everytime the URL changes
  • What needs to happen somehow is that when the filter or search changes while navigating to a list it loads fresh data
  • But when navigating to the detail route , it checks if the id is present in the list of items we currently have and only issues a fetch request if that id doesn't exist

Questions


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>