Initialize Fetch State0:00
At some point you're going to have to fetch data from an API, whether it's an external API or your own API, so let's take a look at how we can do that within Svelte. So we'll make use of the JSONPlaceholder API, and I believe there's an endpoint here for users. It returns 10 users, so we'll make use of this. And I do have a blank Svelte app running here. So let's go into the code. Let's just get rid of some of the boilerplate here. Let me just change this to a div. We'll get rid of all of this. Let's get rid of the prop here. So let's go into main.js and not pass any prop. Okay, so like I said, we're grabbing information about our users, so let's go ahead and define state for that. Say let users. Usually you want a loading state, so let's define that as well. You might not even need this, but let's just define it for now. And we also want to keep track of our errors. So let's say let errors.
Build Fetch Function0:47
You might not even need this, but let's just define it for now. And we also want to keep track of our errors. So let's say let errors = error. Now let's define a method that actually fetches the data from an API. So we'll call it fetchData, no params. And we'll make use of fetch here, but something like Axios would work as well. We'll also use async await. So let's make this function async. Let's say const response = await fetch(). And the endpoint is here. Let me just grab that. Space that in. And let's just do some quick error checking here. So if the response is not okay, then just throw a new Error. So throw new Error(). And we'll just pass in the statusText, response.statusText. Okay. But if it is okay, then go ahead and assign our users to the response.json(). You have to await this as well, response.json(). But we also want to make sure
Fetch on Component Mount1:39
response .status text. Okay. But if it is okay, then go ahead and assign our users to the response JSON. You have to await this as well, response .JSON. But we also want to make sure we handle the error case. So let's wrap this in a try catch. So try all of this, catch the error. And if there is an error, we'll just assign our variable here to some generic message. So say sorry, there was an error. Okay, let's save that. Now depending on how you fetch your data, you're going to want to call this method at some point. For our case, we just want to fetch the data right when the component loads. So we'll make use of the onMount lifecycle hook to do that. So we'll say onMount. Let's hit tab here. That should have imported from Svelte. And let's just call that method. So fetchData. And just to make sure everything is working. Let's console.log the users here. Okay. Save that. Go back to our browser. Let's open up DevTools here. And we do
Render Users List2:33
call that method. So fetch data. And just to make sure everything is working. Let's console.log the users here. Okay. Save that. Go back to our browser. Let's open up DevTools here. And we do get an array of 10 users. Now let's go ahead and display them within our template. So I have this div here. Let's make an unordered list that will display them. So let's say <ul>. And for each user, we can have a list item for that. So we can use each here. So we'll make use of our snippets as each. Okay, we have our users variable. Let's say as user. And we can just make a list item here. And it can be user.name, that should be fine. Okay, let's save that. However, initially, this users variable is null. So we have to check for that as well. So let's make an if else block here. So if else block. So the condition is if there are users, so if users, then we can grab this, put that in here. But if there isn't, that means the app is in a loading state.
here. So s dash if else block. So the condition is if there are users, so if users, then we can grab this, put that in here. But if there isn't, that means the app is in a loading state. So we'll just say div loading. So if we save this, take a look at the browser, there are our users. If I refresh here, you can see the loading indicator flash really quickly. Let me just turn on throttling here, so it's easier to see. So if you go to network, you can see my throttling is set to fast 3G. So now if I refresh, it should be easier to see. There it is. Cool. So the loading indicator is just within this else block. So we don't really need that isLoading state up here. But if you need it within the script somewhere else, then you can go ahead and set it to true right before we hit the endpoint. And then set it to false maybe in a finally block here. But I'm okay with what we have here. Now how about the error
Handle Error and Loading4:26
then you can go ahead and set it to true right before we hit the endpoint. And then set it to false maybe in a finally block here. But I'm okay with what we have here. Now how about the error case. So we can simulate an error by mistyping the endpoint. So let me do that. Okay, and we can check for an error in the else if case. So let me do that here. So let's say else if colon else if the condition is if there's an error, and we can just display it in a p tag here. Let's say error. Okay, save that. Let's see if we get an error within here. And we do. So again, let me refresh, we get the loading indicator. And then we get an error. So let me just put the endpoint back to what it was before. And this is typically how you would handle data fetching to find some state for it and use some conditionals within the template to either show the actual data coming back or a loading state or the errors. Now this is totally fine. But another option would
Use Await Blocks5:21
find some state for it and use some conditionals within the template to either show the actual data coming back or a loading state or the errors. Now this is totally fine. But another option would be to make use of await blocks. So what we can do is wait for the promise to resolve within our template, and then display the corresponding data accordingly. So if we do it that way, then we need to make a few changes. So let me comment this out. And we'll make another div here for the await blocks. So let's say div here, we no longer need our state. So again, we'll comment all of these out. We don't need to call our method on mount. So let's comment that out as well. But we still need our fetchData method here. But we do need to make a few changes. So I'm going to duplicate this and make those changes. And we'll call it fetchDataTwo. So we no longer need to try catch here because that will happen within the await blocks within the template. So let's get rid
duplicate this and make those changes. And we'll call it fetchData too. So we no longer need to try catch here because that will happen within the await blocks within the template. So let's get rid of that. We still need to use fetch here. So we can keep this line here, we don't need this. So let's comment that out. This can be a local variable. So let's say const users equals await response.json(). Let's check the response again here. So if response.ok. So in this case, we can just return the users here. So return users. But if it's not okay, we can say else, throw new Error. And again, we can just say response.statusText. And we don't need this line down here. Okay, so let's save that. And now within our template, we can make use of those await blocks. So let's use this div down here.
Okay, so let's save that. And now within our template, we can make use of those await blocks. So let's use this div down here. Let's use our snippets. So s dash, I believe it's a switch catch block. So now we can await that promise directly in our template here. So what's our promise? Our promise is that fetchData to method or fetchData you can see the comment says promise is pending. So in our case, this will be the loading state. So say loading. And once the promise resolves, we should get our users back. So let's say users. And we can just list out our users like we did up here. So let me just grab this space that in here. And then within our error block, we can just output the error as well. So again, I'll just hard code something in here. So we can just say sorry, there was an error. So again, almost the same as above. But now we're making use of an await block.
Fetch via Svelte Store9:25
server again. Let's import that up here. Let's get rid of these comments here. And I'll put this underneath our fetchData too. Right here, let me paste this. Let's rename posts to users. And this endpoint is correct, but this is users. You can also destructure the errors from here as well. So it's an error. But let's rename it to errorThree, in our case. And you can also grab the loading state from here as well. So let's say isLoading. But let's rename ours to isLoadingThree. Okay, let's save that. And let's go down to our template again and make use of these variables. So again, I will comment this out. We'll make a new div here. And I'll just make use of if blocks here to show them working. So we'll say as if. So we'll start with the loading state. And we need isLoadingThree. But to make use of those variables, we have to use the dollar sign. So $isLoadingThree. And we can say div loading. Okay, so same for the actual data.
need it is loading three. But to make use of those variables, we have to use the $ sign. So $ sign is loading three. And we can say div loading. Okay, so same for the actual data. So say if usersThree, then go ahead and display them. So we can just grab this, paste it in here. And this should be usersThree as well. It looks like I didn't name it usersThree. Let's make sure I did. So let's change this to userThree, not to be confused with the other variables we had earlier. And let's handle the error case as well. So again, as if errorThree with a $ sign, then we can just display some error message here. Okay, let's give that a try. Let me just refresh to see it one more time.
