Cannot read properties of undefined (reading 'map') when using context with a nested Promise object
#17325
Unanswered
sirkostya009
asked this question in
Q&A
Replies: 1 comment
-
|
The issue is that When you use Workaround 1: Store the Promise itself <!-- Parent -->
<script>
const dataPromise = $derived(import(`$lib/${params.key}.js`));
setContext(key, { get data() { return dataPromise; } });
</script>
<!-- Child -->
<script>
const ctx = getContext(key);
</script>
{#await ctx.data}
Loading...
{:then module}
{module.default}
{/await}Workaround 2: Use a reactive store <script>
import { writable } from "svelte/store";
const data = writable(null);
setContext(key, data);
$effect(() => {
import(`$lib/${params.key}.js`).then(m => data.set(m));
});
</script>Workaround 3: Pass a getter function <script>
let moduleData = $state(null);
setContext(key, { get value() { return moduleData; } });
$effect(() => {
import(`$lib/${params.key}.js`).then(m => moduleData = m);
});
</script>The key insight is that context is set once during init, but you can pass a reactive reference (store, getter, or Promise) that updates later. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to use context to bypass using load functions for some specific data to avoid sending a very large response on initial, server-rendered response.
I saw in docs that I can set reactive objects to context, so I have tried to dynamically importing a module into a
$derivedobject, setting it to context, and in subsequent components consume said context with the new experimental await feature.$derivedbecause in my actual case I load data based on the path param. I expect it to work same as with$state.But I am getting
undefinedwhenever I call the getter function!Here's the repro of the issue:
https://github.com/sirkostya009/svelte-context-repro (navigate to
/a/nested)I am not even sure if this is a bug or not. I have initially tried to just
await importin thesetContextcallbut kept getting a "can only call
setContextduring component initialization" error so came up with a clever workaround that also doesn't work!Beta Was this translation helpful? Give feedback.
All reactions