I'm trying to update svelte store with an array of users fetched from server:
const fetchUsers = async () => {
const resp = await fetch(baseUrl + "/users/");
if (!resp.ok) {
throw new Error(`HTTP error ${resp.status}`);
console.log(Error);
} else {
users = await resp.json();
$UsersStore.update((currentState) => {
return [...currentState, users];
});
console.log("users are:", users);
console.log("$UsersStore is:", $UsersStore);
}
};
The store is defined as follows:
import {writable} from 'svelte/store';
const UsersStore = writable ([]);
export default UsersStore;
The console log values are like:
users are: (4) [{…}, {…}, {…}, {…}]
$UserStore is: [Array(4)]
So when I iterate over users
{#each $UersStore as user}
<div> {user.username} </div>
{/each}
I get undefined.
I also tried things like
UsersStore.update((currentState) => {
return [currentState.push(users)];
But that did not work either.
I'm wondering how can I fix this?
Well, basically I needed to concatenate the users array to the existing store:
UsersStore.update((us) => {
return us.concat(users);
});
I'm not sure its the idiomatic way to update the svelte store but it works nonetheless.
Hopefully this help others too, because I had not seen any such example involving setting fetched json data to store in existing tutorials.