Alpine.js Crash Course #11 - Alpine Lifecycle

Net Ninja · Beginner ·🌐 Frontend Engineering ·1y ago

Key Takeaways

This video tutorial series covers Alpine.js, a JavaScript framework used to create dynamic and interactive user interfaces, with a focus on its lifecycle hooks and directives such as x-data, x-model, and x-for. The tutorial demonstrates how to fetch data, update the page, and react to property changes using Alpine.js lifecycle hooks and watchers.

Full Transcript

Okay, then my friends, we have nearly reached the end of this course and I feel like we've covered quite a lot of ground, but there's just a couple more things I want to show you before we finish. And both of these things kind of relate to the life cycle of any Alpine component you make. And by component, I mean any root element that you add the x-data directive to along with all of its children elements as well. So, to demonstrate these two things, we're going to work not with the form that we made previously, but with a different HTML template which I've already created here. So, we have a div tag with the x-data directive already applied to it and notice the value of that is demo, which is a reference to the Alpine data I've already set up and I'll show you that shortly. Anyway, inside that div we've got two different sections. The first section is just a placeholder for where we're going to dynamically output some fetched data shortly. And the second section is an input field which later will use to update the page background color on the fly. Also, notice this x-model directive which keeps in sync with a property called BG. So, both of these different sections are going to allow me to demonstrate different life cycle features of Alpine. Now, in the JavaScript file, we already have the data object set up called demo and inside that we've got two properties defined. Posts, which is an empty array, and BG. So then, the first thing I'd like to show you is a life cycle hook called init which Alpine automatically fires when a component first gets initialized. So, think of this data we're creating right here and the element it's associated with, that div, as a component, two parts of a component. And when the page loads in the browser, Alpine initializes this component. And it's at this point that it automatically fires the init function if we have it defined within this component data object. All right? So, let's make that init function first of all by coming down here and call it, surprise surprise, init. And that's important, you must call this init because that's the function Alpine looks for. And then inside this function for now, let's just log something to the console by saying console.log and then inside that we'll just say init. All right, and then in the browser I'm going to refresh and as soon as Alpine initializes this component, we should see init over here in the console, which is pretty much right away. And we do, init. Awesome. So, it's firing that function straight away. Okay, so we know this init function runs right away when Alpine initializes the component, but what use is it? Well, we could use this function to fetch some data that we want to show on the page because that data is going to be fetched then right away as soon as the component initializes. So, let's do that. I'm going to paste in a simple fetch right here using just the fetch API and all this does is grab some fake JSON from the JSON Placeholder site in the form of post objects. And then when we have that, we update the posts property on this Alpine component to be equal to that parsed JSON data. So, now that post property would be an array of JavaScript objects where each one represents a single post, right? So, Alpine fires this init function as soon as this component gets initialized and inside that we fetch some data and update the post property with that data. And therefore, we could output those posts now in the template. So, let's go back to the HTML file and do this. Now, the way we're going to get those posts on the page is by using a loop like we've seen previously. And that way we can just loop through the blogs property or the posts property, I think it's called, which is an array, remember, and we're going to output a little bit of template for each one. So, we can make the template tag first of all and then we are going to use the x-for directive on it. Now, as a value, we can say post in posts. And we should also give this a key property and bind to it just in case these posts ever get reordered. They won't do, but it's good practice. So, for the value of that key, we can use the ID property which comes along for the ride on each post object. All right, and then inside this template tag, we can just output an LI tag for each post that we have. And on that tag, we're going to use the x-text directive to inject some text content, which will just be the post title. So, just write post.title to output that. And this title property, by the way, is something JSON Placeholder provides to us. All right? I've not made it up. Okay then, so now when the page loads in the browser, Alpine should trigger the fetch request by running the init function. And when we get the data back, we should see it then output on the page. Okay, and there we go, my friends. Now we can see these five post titles right here. And if we refresh, you're going to see that they come in pretty much immediately. It just takes less than half a second to fetch those and output them to the screen. Okay then, so the last thing I want to talk about is how we can watch properties and react by firing a function when they change. For example, we've got this BG property right here, which is an empty string to begin with. And currently, this is bound to the input field in the HTML because we use the x-model directive to hook it up. So, whenever a user types into the input field, it's going to update the BG property in real time. Now, the idea behind this is that whatever a user types in a color, like red or blue or even a hex code into the input field, we're storing that color in the BG property, right? Then, I want to watch the BG property for whenever it changes and I want to run some code to update the background style of this page whenever it does. So, how do we do this? Well, we can use a special watch function in Alpine to watch a property and react to it. So, we're going to set that watcher up inside the init function so that we're watching the BG property from the get-go. And we can do this by saying this. dot and then it's dollar sign watch. And then we want to invoke this watch method. Now, as a first argument to this method, we say which property that we want to watch. Now, in our case, it's the BG property. And as a second argument, we pass a function which runs every time this BG property value changes. Now, as arguments to this callback function, we automatically get access to the new property value, which we just changed to, and we're going to call that new BG, and the previous property value which we changed from, which I'm going to call old BG. Now, we don't actually need the previous value inside this function, old BG, but it's there if you did want it. What I'd like to do then is update the background color style of the page when the value changes. And to do that, I can say document.body and then use the style property on that. And the style I want to change is the background color. Okay? And we want to set it equal to whatever the new BG value is, which we have access to. And this line of code is standard JavaScript stuff, nothing to do with Alpine. We're just updating the background color of the body tag. All right? So, now we've got a watcher set up to watch the BG property and whenever that property value changes after we type into the input, it's going to fire this function to try and update the background color to be whatever that value is. So, let's try it out. All right, so moment of truth. What shall we change this to? Let's go for pink. Yep, that works. Awesome. Let's go for light blue. Cool, that works. And now let's do a hex code. I'm going to say 4789F2. And yep, that updates as well. Awesome. Okay then, my friends. So, that is the end of the series then, but there is still a lot more to Alpine that I've covered in these lessons. This was more of an introduction course than a deep dive. So, definitely check out the docs to learn more about it now you've got the basics under your belt. Also, I will be releasing courses in the near future, like I mentioned at the start of this series, which incorporate Alpine.js into those projects. So, if you like this one, then definitely stay tuned for those. [Music] [Music] [Music]

Original Description

In this Alpine.js tutorial series, you'll learn what Alpine is, and how we can use it to create dynamic, interactive and reactive user interfaces. 🔥🥷🏼Get instant access to ALL premium courses on NetNinja.dev: https://netninja.dev/ 🔥🥷🏼Get instant access to This Alpine Course on NetNinja.dev: https://netninja.dev/p/alpine-js-crash-course 📂🥷🏼 Access the course files on GitHub: https://github.com/iamshaunjp/alpine-crash-course 🔗👇 Alpine docs: https://alpinejs.dev/start-here 🧠🥷🏼HTML & CSS Crash Course: https://www.youtube.com/watch?v=hu-q2zYwEYs&list=PL4cUxeGkcC9ivBf_eKCPIAYXWzLlPAm6G 🧠🥷🏼JavaScript Masterclass: https://netninja.dev/p/modern-javascript-from-novice-to-ninja
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This tutorial series introduces Alpine.js and its lifecycle hooks, demonstrating how to create dynamic and interactive user interfaces. It covers the use of directives such as x-data, x-model, and x-for, as well as the implementation of watchers and reactive properties. By the end of the tutorial, viewers will be able to create their own dynamic user interfaces using Alpine.js.

Key Takeaways
  1. Call the init function when a component first gets initialized
  2. Use the init function to fetch data and update the posts property
  3. Use the x-for directive to loop through the posts array and output a template for each post
  4. Use the x-model directive to keep the BG property in sync with the input field's value
  5. Set up a watcher to watch the BG property and run a function when it changes
  6. Update the background color style of the page dynamically
💡 Alpine.js lifecycle hooks and watchers can be used to create dynamic and interactive user interfaces that react to property changes and user input.

Related Reads

Up next
How To Build A Twitter Clone - React Next JS - Appwrite Crash Course
Adrian Twarog
Watch →