r/sveltejs•
tonydiethelm

How do I fetch something and stick it in state?

I can make state, per all the doc/tutorial examples, easy peasy...

const myState = $state('blah');
const myOtherState = $state({text: 'blah', number: 5})

Great. Easy. Fine. That's fine for a tutorial, but not for a real thing where I'm fetching data and doing Stuff with it.

I can very easily grab data in a page.js/page.server.js file and stick it into state when the page is made. Easy peasy...

let { data } = $props();   //getting {text: "I am text", count: 3} from load function. 

let myState = $state(data);

Great. Works fine when I want to do something once at first page load. Cool.

But what if I want to load my page, take some input from the user, do a fetch based on that, and cram that data into state?

<script>
    let { data } = $props();   //get {text: "I am text", count: 3} from load function

    let myState = $state(data);

    async function fetchSomethingAndStickInState (){
        const response = await fetch('https://tonydiethelm.life/dice/api/1/20');
        const fetchedData = await response.json();
        myState = {text: "I am new text", count: fetchedData};
    }
</script>


<button onclick={()=> myState.count++}>state.count is: {myState.count}</button>

<button onclick={fetchSomethingAndStickInState}>Click this to fetch and attempt to write to state.</button>

Oh, that actually works fine too. Neat. Ok....

Am I missing anything?

What about shared state? If I'm importing state from another file, I can't overwrite that. So what good is shared state? I can't ever change it except for the declaration, which is almost useless in the real world. Or am I confused?

Thanks all! Y'all are amazing Rubber Duckies, and I appreciate you. Fuck AI.

Posted Oct 7, 2025, 2:43 AM UTC

613
Loading comments…