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

Sharing state with runes when assigning the value from async

$
0
0

I am a bit new to those stuff and not sure if my approach is wrong. I would like to have a class and the schemaData needs to be loaded from an async request.But when I am getting the schemaData the state is not being updated after the updateSchema.

// SchemaManager.tsexport class SchemaManager {    schemaData: SchemaData = $state<SchemaData>({});    updateSchema(data: any) {        this.schemaData = this.organizeSchemaData(data);    }}const SCHEMA_KEY = Symbol("SCHEMA_DATA");export function setSchemaState() {    return setContext(SCHEMA_KEY, new SchemaManager());}export function getSchemaState() {    return getContext<ReturnType<typeof setSchemaState>>(SCHEMA_KEY);}
// layout.sveltesetSchemaState();const schemaManager = getSchemaState();onMount(async () => {    try {        const response = await fetch("/json-schema");        if (!response.ok) {            throw new Error(`HTTP error! status: ${response.status}`);        }        schemaJson = await response.json();        schemaManager.updateSchema(schemaJson);        // console.log(schemaManager.getType("OBJECT", "Query"));    } catch (e) {        error = e instanceof Error ? e.message : String(e);        console.log("error", error);    }});
<!-- TextDecoderStream.svelte --><script lang="ts">    import { getSchemaState } from "$lib/utils/schemaToJsonUtils.svelte";    const schemaManager = getSchemaState();    const currentSchema = schemaManager.schemaData;    console.log("schema", currentSchema);</script>

the console.log here is only {} empty object, it doesnt get triggered after the updateSchema. I tried having my setSchemaState inside the onMount but it doesnt allow me to have context there.

Can you let me know what approach shuld i take.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



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