Help with shared $state for API
Hi. I'm new to Svelte but trying to develop a Sveltekit project that receives data via http PUT request from an external C++ application, updates a shared reactive object accordingly, and displays the updated data. Ultimately, a dashboard of sorts.
And it's almost working. But, it seems like the received PUT data is getting over-written constantly by the initialization value from the exported/imported $state object. When I hit the browser refresh button, the correct, latest PUT value (a positive integer representing time as HHMM) is displayed briefly, but is immediately replaced by the initialization value (-1) again. What I want is for the saved/displayed value to remain until the next PUT updates it.
I built a toy version at SvelteLab (since the SV5 REPL does not support):
[https://www.sveltelab.dev/v30x683n47fzr90?files=.%2Fsrc%2Flib%2FZL\_State.svelte.ts%2C.%2Fsrc%2Froutes%2F%2Bserver.ts%2C.%2Fsrc%2Froutes%2F%2Bpage.svelte](https://www.sveltelab.dev/v30x683n47fzr90?files=.%2Fsrc%2Flib%2FZL_State.svelte.ts%2C.%2Fsrc%2Froutes%2F%2Bserver.ts%2C.%2Fsrc%2Froutes%2F%2Bpage.svelte)
The external PUT requests are not implemented there, so of course it will not work. But at least the code & structure should be clear.
In case the SvelteLab demo is not helpful or people don't want to deal with it, the structure & code is also shown below.
Thanks in advance for any guidance!
\-----------
./lib
ZL\_State.svelte.ts
export const ZL\_State = $state({
time: -1,
/\* ... more later ...\*/
});
./routes
\+server.ts
import { json } from '@sveltejs/kit';
import { ZL\_State } from '$lib/ZL\_State.svelte.ts';
export async function PUT(event)
{
let now = await event.request.json();
ZL\_State.time = Number(now);
if (Number.isNaN(ZL\_State.time))
return json({ time: now }, {status: 400}); // bad request
else
return json({ time: now }, {status: 201}); // all good
}
\+page.svelte
<script>
import { ZL\_State } from '$lib/ZL\_State.svelte.js';
</script>
<p>ZL time is {ZL\_State.time}</p>
\---------------