Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Svelte Lifecycle Method - onDestroy

In Svelte, a component's onDestroy lifecycle method is called before the component is removed from the DOM. For example, if you have a component that is wrapped within an {#if} block and it is currently rendered to the DOM, then when this block's conditional statement evaluates to false , the component will be unmounted from the DOM, at which point onDestroy will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that cleanup-related operations can be ran and previous application states can be resumed. Here's a template of how the onDestroy lifecycle method is used inside of a component: Compared to the function returned from onMount , there are specific reasons for using onDestroy : As a vital lifecycle method, onDestroy covers a wide diversity of use cases such as... Below, I'm going to show you: When a modal dialog is closed, the focus should return back to the element that opened the modal dialog. Not doing so would hurt the experience of users who rely on keyboards and/or assistive technologies to navigate through webpages. To rescue the focus: Visit this simple Svelte REPL demo to see how to refocus a previous element using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Modal ( Modal.svelte ) When the "Open Modal" button is clicked, it sets the isModalOpened flag to true , which causes the <Modal /> component to be rendered to the page. When an instance of the <Modal /> component is created, its <script /> block is executed, and previouslyFocused is set to document.activeElement , which references the most-recently focused element (the "Open Modal" button). Notice that the "Close Modal" button in the modal dialog is focused due to its autofocus attribute. When you click the "Tab" key, the focus is trapped within the modal dialog (each press moves the focus to each link, followed by the "Close Modal" button, and back, repeating in a cycle), which prevents the focus from escaping the modal dialog. When you press the "ESC" key or click the "Close Modal" button, then the "close" event is dispatched, which will execute the closeModal function, set the isModalOpened flag to false and remove the modal dialog from the DOM. Before the modal dialog is unmounted, the callback passed to onDestroy will be ran. The focus will resume back to the previously focused element, the "Open Modal" button. Note : In Firefox and Safari, document.activeElement references the <body /> element in an <iframe /> element (where the Svelte REPL displays the result of the Svelte code). In the demo, a reference to the "Open Modal" button is passed to the <Modal /> component as a prop, and it is manually used as the previously focused element if document.activeElement references the <body /> element. Removing event listeners is necessary for avoiding memory leaks in older browsers that don't automatically garbage-collect event handlers of removed DOM elements. A common pattern for registering and unregistering event listeners in Svelte is to perform these actions during the onMount and onDestroy lifecycle methods respectively. Visit this simple Svelte REPL demo to see how to remove event listeners in your Svelte application using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Removing Event Listeners (Window Resize) ( WindowResize.svelte ) Resizing the window updates the printed width value. By debouncing the event handler, the resize event listener will only call the event handler after the resize event has stopped firing for 300ms. Limiting the rate at which the event handler is executed will yield performance gains, especially in much larger applications. To trigger the onDestroy lifecycle method, press the "Toggle" button to toggle off the <WindowResize /> component. This will remove the registered resize event listener on the window object. If, instead, the event listener was binded to an element within the component, then the event listener can be binded to the element in onMount since the element will have been rendered by the time onMount is called. Likewise, the event listener can be removed from the element in onDestroy since onDestroy occurs just before the element is removed from the DOM, which means the element still exists when removing this event listener. To understand how a UI change can affect a user's engagement with your application, you might collect a set of metrics, such as bounce rate and average session duration, via Google Analytics or software custom-built to log this information. A simple metric to integrate into your application is tracking how long a user stays on a page. A rudimentary implementation of this would involve starting a timer the moment the user visits the page, and then stopping the timer the moment they exit the page. Visit this simple Svelte REPL demo to see how to log user activity in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Logging User Activity ( RedditArticle.svelte ) In this example, each tab represents a "subreddit," a topic-specific, online community on Reddit ( r/science , r/technology and r/worldnews ). Clicking on any of these tabs will display a list containing the most popular articles for the corresponding subreddit. The <RedditArticles /> component is mounted anytime the user clicks on any of the subreddit tabs. Upon switching from one subreddit to another, the current <RedditArticles /> component will be unmounted, and a new <RedditArticles /> component will be mounted. The subreddit prop is passed to ensure the articles for the currently selected subreddit are loaded. When an instance of the <RedditArticles /> component is created, this represents the user landing on a new "page," and a timer begins to mark this ( let startTime = performance.now(); ). Once the user leaves the "page" (switching to a new subreddit), the onDestroy lifecycle method is called, and the difference between the time at which the component is unmounted and the recorded start time is calculated. This difference represents how long the user was on this subreddit before leaving. After performing this calculating, the difference can be sent to an API endpoint to be stored. All of the data collected can then be aggregated and viewed inside of a dashboard. Typically, in component-based architectures, data flows downwards from parents to children (unidirectional). In Svelte, stores allow data to be shared between components, regardless of their relationship in the component hierarchy. A store contains a subscribe method that notifies components of changes to the store's value. When the subscribe method is executed, an unsubcribe method is returned, which cancels a component's subscription to a store when called. Visit this simple Svelte REPL demo to see how to unsubscribe from a Svelte store subscription using the onDestroy lifecycle method: onDestroy Lifecycle Method - Scheduling Store Unsubscriptions ( RedditArticles.svelte ) In this example, the "Logging User Activity" demo has been repurposed with the <Subreddits /> component (the tabs) and the <RedditArticles /> component (the list of subreddit articles) both subscribed to a store named reddit . ( store.js ) currentSubreddit represents the currently selected subreddit (by default, it is r/science). Because the value of currentSubreddit can be modified, this store is a writable store, which means two additional methods are provided alongside the subscribe method: set (sets a new value for the store and synchronously executes every active subcription method of the store) and update (updates a value based on the current value in the store). For convenience, a custom method, setCurrentSubreddit , is made available, and it directly updates the currentSubreddit value. All components subscribed to the store will see the changes. In this case, both the <App /> and <RedditArticles /> components are subscribed to the store for changes to currentSubreddit . Imagine a scenario in which a component is mounted/unmounted many times throughout the lifetime of the application. If unsubscribe is not called upon unmounting the component, then its corresponding subscription will still be alive and will be executed upon future updates to the store even when the component the subscription is tied to has been unmounted. Try this out by commenting out the unsubscribe function call in the <RedditArticles /> component's onDestroy and adding a console.log() statement inside of the subscription function. As you switch tabs from one subreddit to another, watch as more and more messages are printed inside of the console. With so many subscriptions still in memory and not garbage-collected, eventually, this will cause a memory leak. To avoid this situation, the unsubscribe method must be called inside of onDestroy lifecycle method. Note : Subscribing to the store and adding a call to the unsubscribe method inside of many components that rely on the store can become tedious and resemble repetitive boilerplate code. Instead, just import the store and prefix a store value with a $ to auto-subscribe to it. The auto-subscription shorthand will allow components to auto-subscribe to the store and automatically unsubscribe from it when the component is destroyed. Check out the <Subreddits /> component for an auto-subscription example. ( Subreddits.svelte ) For third-party libraries such as Leaflet.js that embed interactive maps into an application, the provide methods for "cleaning-up" when they are removed from the DOM. For example, in the case of Leaflet.js, the remove method destroys the map and its layers and clears all of their corresponding event listeners. Visit this simple Svelte REPL demo to see how to clean-up an embedded Leaflet map in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Clean-Up External/Third-Party Libraries ( LeafletMap.svelte ) When the map is toggled on, the <LeafletMap /> component's onMount lifecycle method is called and initializes a new map on a specified container element. Additionally, a marker icon is displayed, and an event listener is added to this icon. Whenever the icon is clicked, a popup opens above it. Once the map is toggled off, the <LeafletMap /> component's onDestroy lifecycle method is called and destroys the map and the marker and clears all of their corresponding event listeners such as zooming in the map, the opening of the marker icon's popup on clicking, etc. When server-side rendering a Svelte application, only one lifecycle method is called: onDestroy . Particularly, onDestroy is called after the application is rendered. For example, when building the static version of a Sapper application via npm run export , only onDestroy is called. To verify this, simply add a console.log statement into each lifecycle method call and observe the outputted logs in the CLI. ( src/routes/index.svelte ) If you have built React applications, then you will have probably noticed how similar onDestroy is to componentWillUnmount . Try rewriting some of those components that use componentWillUnmount as Svelte components that use onDestroy . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onDestroy

Svelte Lifecycle Method - afterUpdate

In Svelte, a component's afterUpdate lifecycle method is called after the component is updated as a result of a state change. When the value of any of a component's props and variables changes, the component's beforeUpdate lifecycle method is executed prior to any DOM updates being made in response to these changes. Once the beforeUpdate lifecycle method is finished running, the DOM is updated to reflect the data changes. After completing this update, the afterUpdate lifecycle method is executed. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that the DOM is completely updated and synced with any new state and prop values. Here's a template of how the afterUpdate lifecycle method is used inside of a component: When using the afterUpdate lifecycle method, remember that it runs on every state and prop change. For components that experience many state and prop changes, it can be quite cumbersome to track which variables/props have changed in order to then execute the appropriate code. This is unlike React's componentDidUpdate lifecycle method , which provides the previous props and state as arguments. Below, I'm going to show you: The Markdown syntax formats plain text into structured content that can be published to the web as valid HTML markup. Commonly, developers write API documentation and blog posts using Markdown. To avoid typos and inconsistencies while writing Markdown, tools and editors have been built to instantly live preview the rendered output of Markdown content. Visit this simple Svelte REPL demo to see how to live preview Markdown using the markdown-it Markdown parser library and the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Markdown Editor Here, we have a <textarea /> element on the left for writing Markdown and a <div /> container element on the right for rendering the output of the Markdown. markdown-it provides a render method that accepts Markdown as an argument and returns the generated HTML as a string. This HTML string can be rendered as HTML using the @html template syntax . Anytime an HTML string is rendered via the @html template syntax, the HTML string should be sanitized (before rendering) to prevent cross-site scripting, especially if the original source is untrusted. Pass the result of md.render as an argument to the sanitizeHtml function of the sanitize-html library to remove malicious HTML code. Changes to the value of markdown (bound to the <textarea /> element via the bind:value directive) will trigger the afterUpdate lifecycle method, which will take this value and convert it to stringified HTML that is sanitized. This result will be rendered as HTML. As you type Markdown into the <textarea /> , the output of the Markdown will be displayed and live updated, giving you immediate feedback on your Markdown. Note : Alternatively, this same behavior can be achieved by using a reactive statement. Many websites provide a theme toggle to dynamically change their appearance based on a user's color preferences. To implement theming, use CSS variables and change the value of those variables whenever a different theme is selected. Visit this simple Svelte REPL demo to see how to toggle themes using the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Theme Toggle Using a <div /> element with a class body to serve as a pseudo <body /> element, it has a background-color CSS property set to var(--background-color) and a color CSS property set to var(--color) . These theme values are pre-defined in an object themes , and whenever any of these two buttons are clicked, the toggle function is called, and the theme variable is set to either themes.dark or themes.light (depending on the button clicked). When theme is updated, the afterUpdate lifecycle method is called, and the values of the CSS variables are updated accordingly. Note : Without label in the theme object, the afterUpdate lifecycle method would not be called because the theme object would not referenced anywhere in the HTML markup of the component. Note : Alternatively, this same behavior can be achieved by using a reactive statement. From top to bottom, chat clients display messages in ascending order of their timestamp, with the oldest messages at the top and the most recent messages at the bottom adjacent to the "Send Message" input field. When a new message is received within a chat client, the user is automatically scrolled to that message at the bottom of the scrollable view, assuming that they haven't scrolled beyond a certain threshold that indicates the user browsing through older messages. Visit this simple Svelte REPL demo to see how chat clients auto-adjust a user's scroll position upon receiving a new message using the afterUpdate lifecycle method: Demo - afterUpdate Lifecycle Method - Auto-Adjust Scroll Position in Messaging Client ( ChatClient.svelte ) In this demo, there are two chat clients, one for a user named "Jesse" and another for a user named "Alex." Whenever any one of these two users sends a message, the message will be displayed in both clients since these messages are based on a conversation between these two users. Messages sent by the user are styled with a blue background and white text, while messages received by the user are styled with a light-grey background and black text. The <ChatClient /> retrieves these messages from a store: When the user submits a new message, the addMessage method will be called to concatenate a new message to the messages array, and the input field where the user types messages will be cleared. Because the messages array is modified (and is used to render messages), the beforeUpdate and afterUpdate lifecycle methods are called. beforeUpdate is called to determine whether or not to automatically scroll the user to the bottom of the <div /> container element (reference stored in messagesContainer ) to see the new message. If the user is within 20px of the bottom-most scroll position of this container element, then the shouldAutoScroll flag will be set to true , and the client will automatically scroll to the bottom of this container element so that the user can see the latest received message. This must be done before the DOM is updated with the new message because adding a new message will increase the scrollHeight by more than the 20px threshold (due a message's minimum height), and thus, cause the calculation to keep assuming that you are browsing through older messages even though you are not. Once the DOM is updated with the new message, the afterUpdate lifecycle method will be called, and it will scroll to the bottom of the container depending on the value of the shouldAutoScroll flag. To animate an element, the element must sequentially transition from a starting state to an ending state. For example, you may want to move a square from the top-left corner (starting state) of a view to the bottom-right corner (ending state) of a view. In between these two states, there may be intermediate states that the element must fulfill. For example, maybe you want the square to move in a zig-zag motion towards the bottom-right corner rather than in a straight diagonal motion. Additionally, parameters such as duration , timing function and delay must be factored into each step. Referring back to the square example, each step in the animation requires knowing the most recent (x, y) coordinates of the square's position and the (x, y) coordinates of the square's next position in the zig-zag motion. And this continues on for each adjacent pair of steps in the animation sequence. At each step, you would cache the current coordinates of the square and calculate the difference between these coordinates and the next coordinates of the square. Using the calculated displacement (and other parameters like the ones mentioned previously), the square can be animated from point A to point B. In Svelte, animating an element can be done using the beforeUpdate and afterUpdate lifecycle methods. The below snippet of code is based on a demo presented at Svelte Summit 2020: In the beforeUpdate lifecycle method, before each DOM update, the current coordinates ( x and y ) of the animating element ( node ) are cached. In the afterUpdate lifecycle method, after each DOM update, the cached coordinates are subtracted from the current coordinates to determine how far away these coordinates are from one another ( dx and dy ). Then, either a spring-based (via createSpringAnimation ) or keyframe (via createKeyframes ) animation is performed (via node.animate ) using these calculated differences ( keyframeFn({ dx, dy }) ). Visit this Svelte REPL demo to see this in action: Demo - afterUpdate Lifecycle Method - Custom Svelte Action - Shuffle Animation Note : This demo is based on the Svelte Summit 2020 demo. In this demo, pressing the "Shuffle" button randomly rearranges the cat pictures in a two column masonry grid layout (columns are 300px in width). The pictures are smoothly translated from one slot to another. Each picture <div /> element is attached element-level lifecycle methods via a Svelte action ( translate.action , prefixed with the use directive). These methods are called when the element is created, destroyed, etc. Here, translate.action is assigned the translateElement function, which contains the exact same code as previously mentioned with the beforeUpdate and afterUpdate lifecycle methods. ( translate.js ) If you continuously press the "Shuffle" button, then the pictures will be shuffled around until the "Shuffle" button is no longer pressed, at which point, the pictures will be able to animate to their designated new slots. This "shuffling around" behavior is made possible by the following code that uses the afterUpdate lifecycle method. The tick function is called ensure that all pending state changes have been reflected to the DOM. Then, translate.flush executes all of the animation steps queued via the syncLayout.read and syncLayout.write methods in the translateElement function. This allows the translation animation to be ran smoothly irregardless of interruptions. If this block of code was commented out, then the pictures would "blink" immediately to their designated new slots. Note : Alternatively, you can use one of Svelte's built-in animation directives such as flip . If you have built React applications, then you will have probably noticed how similar afterUpdate is to componentDidUpdate / useEffect . Try rewriting some of the those components that use componentDidUpdate / useEffect as Svelte components that use afterUpdate . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - afterUpdate

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Svelte Single-Page Applications with Svelte Router SPA

Single-page applications (SPAs) provide user experiences that mirror those on desktop/mobile applications. Navigating from one page to the next no longer requires waiting for the browser to fully refresh the page on each transition, which keeps users engaged and productive. Because only a single page is served to a user, only certain sections of the view are dynamically updated by the browser (rather than the entire view via a full-page refresh) when the user navigates to a new page. To coordinate which sections of the view are dynamically updated for each route a user can navigate to, the single-page application must leverage a router to map these updates to each possible URL and render accordingly. When a router is added to an application powered by a modern front-end library/framework, such as React.js and Svelte, developers are able to quickly build single-page applications due to the declarative APIs offered by these libraries/frameworks. Compared to applications built with React.js, those built with Svelte are smaller (in bundle size) and faster. Svelte's compiler strips out the runtime overhead from outputted bundles and only ships the code that's needed. Additionally, Svelte does not rely on a virtual DOM and diffing algorithms (or other such techniques) for rendering updates. Instead, Svelte's compiler can determine ahead of time which parts of the application should change for a given state change, and when such state changes occur, it will surgically modify the DOM directly. While not as large as the React.js ecosystem, the Svelte ecosystem continues to grow and gain traction. When considering all of the routers in the React.js ecosystem, there are two that are often chosen for their maturity, robustness and simple-to-use APIs: @reach/router and react-router . To introduce the concept of integrating a router into a Svelte application, we will use an "easy to start with" router: svelte-router-spa . Using this router and Svelte, we will be building the following dashboard as a single-page application: To start, download this project from GitHub: This repository was scaffolded from the sveltejs/template project template, and it will contain the all of the dashboard's components and views. We will integrate svelte-router-spa into this dashboard so it can... Install svelte-router-spa as a dependency. To run the application, execute the dev script: Visit localhost:5000 in a browser. As you hover over each navigation bar item, notice that each item has an href value of / . Our objective will be to make these items link to their correct corresponding routes and render the correct page view. To preview any of the other page views, go to the src/layouts/DashboardLayout.svelte and swap out the current <Home /> view with another view. Example : Preview the <Projects /> view. ( src/layouts/DashboardLayout.svelte ) The browser should automatically refresh the application to reflect this change via hot reloading. Note that the title bar does not update to "Dashboard > Project" when the current view is <Projects /> . This also needs to be fixed. This dashboard will support the following routes: Inside of the src directory, add a routes.js file. Inside of this file, let's define the dashboard routes based on the information in the table above: ( src/routes.js ) Each object in routes represents an individual route. For each route, a URL pathname ( name ) is mapped to a Svelte component (directly via component or layout , or indirectly via redirectTo ). Next, let's add the <Router /> component to src/App.svelte to indicate the top-most area in the application where updates will be made to the application when these routes are visited. Anything outside of <Router /> will not be affected. The layout (or component) that matches the current active route will be rendered inside of <Router /> . In this case, when visiting /dashboard (or /dashboard/home , etc.), the <DashboardLayout /> will be rendered where <Router /> is placed. ( src/App.svelte ) Since <DashboardLayout /> is a layout component, it needs to define a place to render the child components defined in the nested routes of /dashboard . Let's add a <Route /> component to handle this. To render the correct child component for the current route, <Route /> must be passed information about the current route (and child routes) via the currentRoute object. This object is passed to the child components it renders. ( src/layouts/DashboardLayout.svelte ) In the browser, visit localhost:5000 . Notice the redirection to localhost:5000/dashboard/home and the <Home /> view being rendered for this route. Now visit localhost:5000/dashboard/projects . The <Projects /> view is rendered for this route. There are currently two issues with the navigation bar: First, let's pass currentRoute to the <Navbar /> component in the <DashboardLayout /> layout component: ( src/layouts/DashboardLayout.svelte ) Next, let's propagate currentRoute to the <NavbarMenu /> component in the <Navbar /> component: ( src/components/Navbar.svelte ) With the removal of the dashboardRoutes prop, we will need to directly import the list of routes into the <NavbarMenu /> component to render the navigation items. Currently, routes is not formatted properly for this task. We will need to refactor the routes.js file to export a dashboardRoutes array, which will be used only to render these navigation items, and add a custom flag ( isExcludedFromNav ) to the "projects/:id" nested route object to tell <NavbarMenu /> to not render it as an item in the navigation bar. ( src/routes.js ) Additionally, we will need to pass the currentRoute object to the <NavbarMenuItem /> component. ( src/components/NavbarMenu.svelte ) Inside of the <NavbarMenuItem /> component, the isActive flag determines whether or not to highlight the navigation item when its corresponding route is the current active route. svelte-router-spa provides a useful method for determining if a path is the current active route: routeIsActive . It accepts two arguments: In this case, we would want the match to be exact. The currentRoute has been passed to the <NavbarMenuItem /> component to trigger a reactive statement that will set the isActive flag whenever currentRoute changes. If the user clicks a navigation item, then the active status of the item should be changed to reflect the new current route. Hence, the following statement will correctly set the isActive flag whenever any of the navigation items is clicked: Alternatively, you could substitute the <a /> element with the <Navigate /> component (a wrapper around an <a /> element) from svelte-router-spa to automatically add an active class if the route specified for to is the current route. All-in-all, the following changes to the <NavbarMenuItem /> component are the most comprehensive: ( src/components/NavbarMenuItem ) Verify that the navigation items work properly. Verify that the active class automatically being set as a result of using the <Navigate /> component. Extra Challenge : Make these same adjustments to the mobile navigation bar, which can be viewed when the browser width is less than 768px. These are the files that need to be modified: src/components/NavbarMobileMenu.svelte , src/components/NavbarMobileMenuItem.svelte and src/components/Navbar.svelte . Notice that the title bar is not updated to reflect the current route as you navigate from one page to the next. Unfortunately, the currentRoute object does not provide a route label. Let's export a new method, getRouteLabel from src/routes.js to retrieve the current route's label. routesMapping.withoutParams is an object that maps a route's pathname to its label. For example, /dashboard/projects is mapped to "Projects." For routes without namedParams , getRouteLabel will check routesMapping.withoutParams for an exact pathname match and return a label for the matched pathname. For routes with namedParams , getRouteLabel will check an array of [ regular expression, label ] pairs and test the pathname against each pair's regular expression. The label of the first test that evaluates to true will be returned. If no matching routes are found, then an empty string is returned as the label. Import getRouteLabel into the <TitleBar /> component, and set its value to currentRouteLabel via a reactive statement. This ensures the value of currentRouteLabel is updated whenever currentRoute has changed. ( src/components/TitleBar.svelte ) Verify that the title bar is updated whenever a navigation bar item is clicked. Let's apply the same reactive statement to each view component to render the correct label in the placeholder content. ( src/views/Board.svelte , src/views/Calendar.svelte , ..., src/views/Timeline.svelte ) Verify that the correct label is rendered. Currently, the "Edit" link for a project listed under /dashboard/projects loads the "Home" view at /dashboard/home . Let's modify the link to load the "Project Info" view at /dashboard/projects/<id> . First, pass the currentRoute object to the <ProjectsTable /> component: ( src/views/Projects.svelte ) Inside of the <ProjectsTable /> component, swap out the <a /> element for the <Navigate /> element. Prefix the link with currentRoute.path . ( src/components/ProjectsTable.svelte ) Verify that clicking on "Edit" loads the "Project Info" view. Inside of package.json , there is a start script to run the production-optimized application. ( package.json ) It uses sirv , which spins up a server to allow you to preview the assets in a specified directory (in this case, public ). Passing the -s option to sirv tells it to treat the public directory as a single-page application. When you refresh the page at a route defined by the router, the route is unknown to sirv , so it will automatically serve the index.html file, which knows how to handle this route. Without this option, this will be loaded in your browser: Inside of routes.js , check if any of the defined routes has layout or component set to a string instead of an imported component. Example : ( src/routes.js ) Notice DashboardLayout is wrapped in quotes. Remove those quotes. Inside of rollup.config.js , pass the following options to the commonjs plugin: ( rollup.config.js ) Experiment! Visit the svelte-router-spa documentation and try adding protected routes to the project. If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Single-Page Applications with Svelte Router SPA

Firebase Authentication with React

In this article, we will learn how to implement Firebase authentication in a React app.Firebase is an increasingly popular platform that enables rapid development of web and mobile apps. It offers a number of services such as a real-time database, cloud functions and authentication against various providers. In the following sections, we will build a React app that has three screens: Let's create a new project on the Firebase Console . We will call our project react-firebase-auth Once the project is created, we will navigate to the 'Authentication' tab to set up sign-in methods. For now, let us enable sign-ins with a username and password. The only other thing left to do before we start building our React app, is to add it to the Firebase project. Once we add a web app to our project, Firebase gives us the app configuration, that looks somewhat like this: We will add these configuration values into the .env file in our app. Let's use create-react-app to generate a stock React app. We'll call our app react-firebase-auth . Once this is done, we need to add a few dependencies using yarn add : In the app's .env file, we need to add the values supplied by Firebase in Step 1 like so: More information about how environment variables work can be found in the Create React App documentation . In the src folder, let us create a base.js file where we will set up the Firebase SDK. In app.js , we will wrap our app with the Router component from react-router-dom which will allow us to use routes, links and redirects. In order to store the authentication status and make it globally available within our app, we will use React's context API to create an AuthContext in src/Auth.js . We will hold the currentUser in the state using the useState hook, and add an effect that will set this variable whenever the Firebase auth state changes. We also store a pending boolean variable that will show a 'Loading' message when true. In essence, the currentUser will be null when logged out and be a defined object when the user is logged in. We can use this to build a PrivateRoute component which allows the user to access a route only when logged in. The PrivateRoute component takes a component prop which is rendered when the user is logged in. Otherwise, it redirects to the /login route. We can now use this in our app.js file after wrapping our app with the AuthProvider : Let us now implement the screens that make up our app. We can start with the simplest one, which is the home screen. All it will have is the title 'Home' and a 'Sign out' button that logs the user out of the app. This is done by calling the signOut method from Firebase's auth module. Let's now move on to the signup page, which is slightly more complex. It will have the header 'Sign up', with a form that includes text inputs for email and password, and a submit button. We wrap the component with the withRouter HOC to provide access to the history object. When the form is submitted, we will use the createUserWithEmailAndPassword method from Firebase's auth module to sign the user up. We display an alert in case something goes wrong during this process. If the user creation succeeds, we redirect the user to the home ( / ) page using the history.push API. The login page is very similar to the sign up page, with an identical-looking form. The only difference is that we will log the user in rather than create a new user when the form is submitted. The component also uses the currentUser value from our AuthContext , and will redirect to the / route when the user is logged in. And there we have it - we have just implemented a React app with sign up, login and home screens that uses Firebase authentication to register and authenticate users with their email and password. We have now learned how to implement Firebase authentication with a React app. The code used in this article is available at https://github.com/satansdeer/react-firebase-auth and a video version of this article can be found on YouTube .

Thumbnail Image of Tutorial Firebase Authentication with React

    5 Reasons to Choose SvelteJS for your Next Project

    Svelte.js is a revolutionary, new JavaScript framework with fast performance, easy-to-learn syntax, and a compile step that doesn't use a virtual DOM so the browser does less work. You can use Svelte as part of a component-based architecture to build projects of any kind, wherever you might use React, Angular, or Vue. Although Svelte.js is a newer framework, several companies have already started implementing it to create fast-loading landing pages, including Spotify. Read on to find out what all the Svelte buzz is about, and 5 reasons why you should choose Svelte for your next project. Svelte is known for being easy to learn and read, but it's also quick and simple to set up a Svelte project. If you already have Git and NPM on your system, then initializing a Svelte project and running it locally only takes a couple of commands: This will create a basic Svelte project in a new folder called my-svelte-project, and run it in a hot-loading local dev environment. This is similar to create-react-app in React, where you can create a template with the files and tools needed to set up a project in one command. Here's a look at the files that are created: With the Svelte template set up, you can run npm install , then npm run dev , and navigate to localhost:5000 to see your app up and running! In a Svelte project, .svelte files are used to define single-file components. Keeping components in single files (organized in directories) with all the logic in one place helps keep even big projects maintainable. A .svelte file consists of a <script> section and any HTML markup you wish to use. You may notice the lack of boiler-plate, which makes the code very readable even for someone who has never used the framework. Here's a sample .svelte file. Any variable declared is automatically reactive and can be used in the markup with single curly braces {varName} . Just as with other JavaScript frameworks, it's easy to make your buttons and DOM elements interactive with event handlers with Svelte. With the syntax on:eventname={handlerFunction} you can listen to any event on an element. Modifiers can also be added to event handlers to change their behavior. Here's a simple button click handler example. And with the once modifier: Event modifiers can also be chained, so that more than one modifier can be added to a single event. Conditional rendering is an essential tool to show or hide certain elements from the DOM based on whether or not a condition is met. In Svelte, Conditional rendering is accomplished with {#if} blocks. Simply add {#if expression} and Svelte will handle the rest. {#if} blocks can also be combined with {:else} and {:else if} blocks for greater conditional functionality. Showing lists or a table of rows from a data source is a very common task in web applications. In Svelte you can iterate and render lists with {#each} blocks, in this case accessing each row, along with the index. Just getting started with Svelte and want to know more about the basics and how Svelte compares to other frameworks? Check out our blog What is Svelte.js and Why Should You Care? Svelte vs React vs Vue . If you want to know more about the background of Svelte, read the Svelte introductory blog post from the framework's author Rich Harris. There's so much to learn when it comes to Svelte, and you can also get started with lots of interactive examples at the official Svelte.js tutorial . If you want to go even further with Svelte you can learn how to build a full-stack web application with Svelte, Express, and PostgreSQL in our new Fullstack Svelte Course !