Reputation: 75
Brand new to Svelte be gentle!
I've followed along with some of the tutorial examples, creating lists of items using each blocks and then removing items, but they all use arrays as the data store then splice/slice etc to remove the items like at;
https://svelte.dev/tutorial/keyed-each-blocks
I am trying to achieve a similar thing with a JSON data store from an async json placeholder request.
Here is what I have so far https://svelte.dev/repl/9d1bc0a8af79459f8ad0cd6c9cb82fa2?version=3.29.4
I am just using regular javascript in the delete function to destroy an element, but I would like to access the animate/transition effects built into Svelete and achieve the same thing in a svelte way.
Any advice and help very welcome. Thanks
Upvotes: 0
Views: 7438
Reputation: 16451
What you do is to not actually return the data from the promise but only a success status, the data itself you save to a separate variable:
let things = []
async function getThings(){
const res = await fetch(`https://jsonplaceholder.typicode.com/users`);
const json = await res.json();
if (res.ok) {
// save the result to json
things = json;
// you can even leave this part out
return true;
} else {
throw new Error(text);
}
}
then you of course loop over the array when the promise has resolved:
{#await promise}
<p>...waiting</p>
{:then success}
{#each things as thing, index (thing.id)}
stuff goes here
{/each}
{/await}
And finally in your delete function you can now manipulate the array:
function onDelete(id) {
things = things.filter(t => t.id != id)
}
On other approach is to separate fetching the data from displaying the data by making it two different components:
{#await promise}
<p>...waiting</p>
{:then things}
<DisplayComponent data={things} />
{/await}
Inside DisplayComponent
your data will now be in a regular array and you can do whatever you want with it. An advantage with this is that you can independently test DisplayComponent
by sending in mockdata.
Upvotes: 0