Svelte 3 Reaction & QuickStart Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
just when I discovered the meaning of life they changed one of my favorite things about JavaScript is that the status quo never seems to last very long react angular and view have dominated the mind share of developers over the last few years salt has been around for a while but they just released version three last week and my initial experience with it has been very positive and that's mostly because it empowers you to solve problems with less code in the first half of this video we'll cover the basic concepts in spelt and in the process you'll see why it's such an awesome tool in the second half of the video we'll build a real-time to-do list with spelt and firebase from scratch if you're new here like and subscribe and you can find the full source code on fire ship IO now before you jump into spelt I'd recommend watching this talk from its creator rich harris that's what really got me excited to start learning spell 3 let's go ahead and just jump right into things will run npx dig it and then point to these felt j s template this is the equivalent to create react app or ng new go ahead and open it up in vs code and run npm install then you can run npm dev to serve it locally and that should give you this hello world on localhost 5000 the first thing you'll see is the roll up config dot j s this is what bundles your code and it's an alternative to web pack personally i prefer to use roll-up but you can also use webpack here if you want and while we're talking about bundling there's two things you should know and that's that spelt supports server-side rendering as well as native web components or custom elements so that's cool but so far this might just look like another JavaScript framework but if we go into the package.json we can see that something's different here what's missing is dependencies we only have development dependencies and that's because spelt is a compiler it generates all of your code at Build time which means it doesn't need to include the framework itself as a hard dependency in your JavaScript bundle another framework that also does this is stencil j/s and I feel like this approach makes a lot more sense than the current status quo and that's because you only need to compile the JavaScript from the framework that you actually need so you don't have any extra bloat in your JavaScript bundle what I'm doing right now is just exporting our entire app as a string and if we go to the bundled output you can see that it's just a function that returns a string so in theory this should result in smaller bundle sizes or at least bundles that are optimized for the code that you actually use if you're using tree shakable libraries that's what makes felt fundamentally different than the status quo but we've only just hit the tip of the iceberg here it's also unique in the way that it handles reactivity if we go into the app component we'll see a script up here at the top that's where we keep our main JavaScript logic and then we a style tag all the styles will be scoped to this component and another cool thing about the compiler is that it will automatically eliminate all of your unused CSS styles from the CSS bundle and then after that we have our markup and spelt has its own templating syntax for adding logic to your HTML this is a similar approach to angular and view but differs from react which uses JSX now the difference with JSX is that you're taking your HTML and putting it inside of JavaScript and letting the JavaScript handle the logic this can be a very divisive topic and it's really just a matter of opinion but I just find I'm more productive by putting the logic at the HTML like we do with angular view and spelled now if we go up into the script you'll notice I have export Latin name using the export keyword in front of a variable means that it can be passed down from a parent component if we leave the export keyword off it basically means we have a private variable that can only be used inside of this component now the cool thing about spelt is that it's reactive based on the assignment of a variable we'll create a variable here for a random number and then create a function that can reassign that variable so now that we have this function we need to bind it to an event in the Dom you can bind to events by doing on colon click or on : whatever Dom event you want to bind to this is very similar to all of the frameworks we passed in the function and it's going to call that function with the event passed as the argument so that's going to change the random number and then we can show it in the template by wrapping it in braces now we have an app that reacts to this randomize button whenever we click it we get a new random number but what happens if we need to compute a different value from this random number let's say if it rounds to 1 it'll be a winner if it rounds to zero it'll be a loser the simplest solution is just to write that expression directly in the template and spelt will rerun this logic every time the reactive value changes but this isn't going to scale very well because we can't reuse this logic if we want to show that same value somewhere else in the template we'd have to duplicate that code fortunately spelt has a very cool trick up its sleeve for computed values we'll define any variable but instead of using let will use this dollar sign colon syntax believe it or not this is valid vanilla JavaScript and it's basically just a way to tell spelt to recalculate this value when the app reacts now we can go back into our template and simply reuse the result computed value as many times as we want now speaking of reactivity another thing we can do is bind to the attributes on Dom elements for example if we want to bind to the value attribute on a form input we can do that with this bind directive and use our random variable if we start typing in the form you'll see how the value itself is recomputed every time we type a new value now currently our computed result is a string but let's go ahead and change that to a number and then we'll show an entirely different template based on some conditional logic the new computed value will give us a number between one and a hundred and we can show a template conditionally by using this if syntax and we can also throw in else if if we have multiple conditions and then else for the default value and then we'll just add some Dom elements in between these conditions and that will recompute the template every time our random number changes so that's pretty standard stuff but now I want to show you something that you're not going to find in other frameworks let's go ahead and import fade and fly from spelt transition these are directives that will allow you to automatically compute CSS animations based on the logic in your template so if you want something to fade in and fade out when it's added or removed to the Dom you can just add this transition fade directive and everything will just happen automatically but let's say we want our poop emojis to fly in from the right and then fly out to the left normally this would take some careful thought about your CSS animations or you might use a JavaScript animation library but in spelt we can use the directives to keep the animation logic tied directly to the Dom element that's being animated and then we can add our own properties to it to customize the way it behaves and that gives us poop flying all over the screen which is the effect we're going for and there's even a directive specifically for SVG graphics that we'll draw the path along the shape so that's really awesome stuff but there's still a couple of other fundamental things that I want to show you before we get to the full demo earlier I mentioned that spelt is reactive based on assignment so if we have an array and then we push new items to the array we won't get any actual changes in the Dom that's because we're just mutating the array and we're not actually reassigning the variable so if you want the app to react to changes to an array or to an object it's generally a good idea to use the spread syntax this code here will do the same thing as a right push but it will also reassign the variable causing the app to react and update the Dom now when working at the Rays you'll probably want to loop over them and display some Dom elements for each item we can do that by using each which will give us access to both the value and the index of each item in the array when we build out our full demo you'll also see that each loops work with asynchronous values similar to the async pipe and angular and speaking of asynchronous values spelt has a really cool way of handling promises I have a helper function here that just creates a delay I'm defining our random value is a promise that results to a random number after that delay when working with promises there's generally three things that happen first you're in some kind of loading state waiting for the promise to resolve then you get a value or maybe you get an error and need to show some kind of error message in spelt you can await a promise directly in the template and this will also handle things like race conditions for you automatically the first section is where you would put your loading spinner while the promise is being resolved then you show the actual result or you catch the error and show an error message and that provides a very readable and intuitive way to handle promises in my opinion it's actually very similar to a future builder and flutter if there's any flutter developers watching at this point now we're going to switch gears into spelt stores which behave very similar to rxjs observables and they can be shared anywhere in the component tree so you have a very easy mechanism for sharing data anywhere in your app let's go ahead and create a writable store and it's very similar to a behavior subject in rxjs at least in terms of its API first we can pass it a default value and then we can set the value directly by calling set or we can call update to get access to the current value and then compute a new value in the stream which we can do with this callback function which gives us the current value then we return the next value and if we just want to listen to the value we just subscribe to it but if you've worked with observables then you know that you need to manage your subscriptions carefully otherwise you could end up with memory leaks if we go back into our component the first thing that we'll do is import the random store that we just created we could subscribe to that directly in the JavaScript but then we would have to dispose of it once this component is destroyed that leads to a lot of boilerplate and also a lot of potential for error but notice how I have this dollar sign in front of the store value itself this will tell the compiler to automatically subscribe to the value and also manage the subscription automatically and now we can push new values to the stream from any component anywhere in the app that will solve a lot of your complex data sharing situations but you can also just pass props directly between a parent and child component I went ahead and created a new component called child and it's just a dumb component that displays some properties now we'll go back up to our app component and pass some properties down to this child let's imagine we have this data object here that we pulled from a database or something now we can go and declare our child component and just pass in each property one by one but even after just three simple properties it's starting to become kind of hard to read but spelt has yet another little piece of magic that will make this code much nicer you can simply send all of your props down to the child using these spread syntax so now that you know some of the basic concepts in spelt I want to put everything together into a full working demo in just a few minutes we'll be able to build this real-time to-do list that also includes user authentication and even some animation once a user is logged in they'll be able to fill out this form with some information about the to do that'll be saved to fire store and they can toggle it complete or incomplete or delete it and of course everything will stay synched up with the backend database we'll be using our Xfire for this demo which you can install with the following command the first thing we'll do is create a file called firebase J s just used to initialize firebase and you'll need to use the credentials from your own firebase project we'll be going through this code very quickly so make sure to follow along with the source code on fire ship io but basically the purpose of this file is just to initialize the app and then export auth and the fire stored database so we can use them in other files from there we'll go into the app component and we just have a few small changes to make here we'll import this login component which will create next and with spelt you'll notice that there's no index.html that you can mess with so instead what you can do is use this felt colon head tag to add additional things to the head of the document in this demo I'm using the boma CSS framework just so we have some better base styles to work with after that we'll build our off features so the user has a way to log in I'm creating a profile component which will just be a dumb presentational component to show the users display name photo URL and user ID and another cool side note here is that svelt will automatically warn you for accessibility issues for example if we leave out the alt attribute it's going to warn us to add one you can also do this in ES lint but it's nice to just have this stuff working right out of the gate after that we can create the logging component which is the smart component that does the actual interaction with firebase now the interesting thing about spelt is that the shape of the stores are similar to the shape of rxjs observables so that means we can use some of that syntactic sugar on rxjs observables in addition to spelt stores currently I'm grabbing the off-state observable from our Xfire and just subscribing to it manually but we'll refactor this in a minute and I'll also define a function here to trigger the pop-up that will allow the user to log in with Google and that will cause the value of the AA state observable to change now we can go down to the template and create an if-else statement and if we have a user logged in we'll go ahead and display that user profile component and of course use that spread syntax to pass the props down and if the user is not logged in we'll just a button that can trigger that login function at this point we have a fully working off system but we can actually refactor this a little bit to use some of spells built-in syntactic sugar this time we'll define the user as the observable itself and then we'll just go ahead and use that dollar sign syntax to unwrap the observable directly in the template that'll work inside the if condition and also works inside these spread syntax and now we have a login component that will manage our subscription automatically with almost no boilerplate now it's time to move on to the to-do list each of the individual to-do items will be represented by this dumb component called to-do item but instead of just displaying data it's also going to emit custom events up to the parent component so this is a way to pass data from a child component back up to the parent and in this case we're doing that so we can tell the parent component when to remove the item from the database or when to update the status in the database spelt has a thing called an event dispatcher which will create a custom event in the Dom for you in this case when we want to remove an item will dispatch an event called remove with that items ID in the database and then we'll do a similar thing to talk about the status of it to-do item but this time we'll pass the ID as well as the new status that the item should change to now I'm defining a CSS class that will show when an item is complete and I'm going to make sure that that class name is the same of the property that toggles that class which is the boolean value of complete on this component and we might as well just add a transition to this item when it's created so it kind of slides in from the right and we can easily do that by simply using spell its transition directive from there we can go ahead and add the text inside the list item and when it's complete we want to show that CSS class spelt has a built in class directive which we can use like this by pointing it to the complete property but if the CSS class and the property both share the same name which they do in this case we can actually make this even more concise like so now the last thing we'll do in this component is create our buttons that will dispatch the custom events we have three different buttons here two of those are used to toggle the status and the other one is used to remove the item and now we're ready to move on to the final component of this app which is the to-do list I'm not going to talk too much about the firebase code basically we're just making a reference to the collection in the database and then making a query for all of the to-do items that are associated with the logged in users user ID then we're going to use the collection data function from our Xfire which takes that query and converts it to an observable of the document data but in order to work with an each loop and belt will also want to pipe and start with and that will guarantee that the observable always has a synchronous array to start with from there we'll define the update status method which will take the custom event that's being emitted by the child component and use it to make an update to the firestore database and then we'll do the same basic thing to handle the remove event now if we go down to the template we'll set up an each loop and notice that I put a dollar sign in front of the two dues observable this will unwrap The Observer will automatically manage the subscription and then react to any new changes whether they happen client-side or on the server and then we can pass our props down to the to-do item component and then we can also listen to the custom events that we defined on that component as well so instead of just doing a simple on click event here we're doing on remove and on toggle again those are custom events defined in the child component and then the very last thing we'll do is set up a form input using the bind value directive and then set up a button that will add that item to the database when clicked and that's all there is to it we now have a reactive real-time to-do app overall I've been super impressed with spelt the only thing that I think is missing at this point is typescript support but from what I understand there should be typescript support in the near future I think what impresses me the most about spelt is that the abstractions are really well-thought-out but they don't take you too far away from the Nilla javascript or native dom api's I'm gonna go ahead and wrap things up there let me know what you think about spelt in the comments thanks for watching and I will talk to you soon [Music]
Info
Channel: Fireship
Views: 207,812
Rating: undefined out of 5
Keywords: firebase, webdev, app development, javascript, lesson, tutorial, svelte, sveltejs, svelte 3, js, jsx, react, angular, vue, svelte tutorial, svelte review, svelte quickstart, svelte crash course, svelte js, rxfire, rxjs, reactive x, reactive programming, complier, js compiler, html
Id: 043h4ugAj4c
Channel Id: undefined
Length: 14min 46sec (886 seconds)
Published: Thu Apr 25 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.