Getting Started with Vue.js in 2020
Resources
- You can watch this documentary and learn about the story behind
Vue.JS
.- Note: this is not a technical tutorial, it’s about the people behind the framework and its evolution.
Duration: 35 minutes
Getting Started with Vue.js in 2020
Vue.JS
.
Duration: 35 minutes
Welcome to the React.JS course. Before diving into the technical nitty-gritty of React, let’s talk a little bit about the history of this popular JavaScript library.
In 2013, React.JS was introduced by Facebook, as a JavaScript library for creating and managing complex user interfaces. It does this by breaking up the interface into independent, composable and reusable chunks of code called Components
, which have their own private memory (called the State
). Components can be rendered inside the Browser, in the server or through a mobile app (when using React Native) depending on the choice and requirements of the application.
On top of that, React uses a Declarative programming style and abstracts all of the DOM manipulation methods away from us. Creating DOM elements, adding Event Listeners and updating the DOM accordingly can be done in a simpler and much easier fashion in contrast to the standard JavaScript DOM API.
Watch the selected part (up to 04:45) of this next video by Mosh Hamedani in which he talks about the history of React and the concepts of Components
and the VirtualDOM
.
React, Components and the VirtualDOM in a nutshell by Mosh Hamedani
How does React manage all this complexity and abstracts away the DOM API?
When working with HTML, each element or section of the interface is composed of multiple nested HTML elements. For example, let’s say we want to have a Subscription
section:
<section class="subscribe">
<h2>Subscribe to our Newsletter</h2>
<hr>
<p class="suscribe--info">Get whenever the latest release of our newsletter directly to your mailbox</p>
<button class="subscribe--action">Subscribe</button>
</section>
Whenever we want to re-use this element in different pages or parts of a page, we need to copy and paste whole chunks of code, bloating our HTML code. Worse than that, whenever we want to update this element in some way we need to search through our codebase, find the recurring element and update it in multiple places, a process that is tedious, and most of all, highly error-prone. Is this breaking the D.R.Y. (Don’t Repeat Yourself) principle? Absolutely!
Facing the problems mentioned above, Facebook engineers came up with the brilliant idea of transforming these recurring chunks of code that belong to a single User Interface (UI), into custom HTML Tags called Components
. Instead of repeating the same code again and again, it is being abstracted away and placed in a separate file, and a single custom Tag name is used instead, whenever we want the code to appear on our HTML pages.
For example, the previous code can now be placed in a separated file named Subscribe.js
(React uses JavaScript to create Components
) and a single custom Tag named Subscribe
or Subscription
can be used in its place, in any page and in any parts of our page. All relevant, element-specific code, including HTML, CSS, media assets and JavaScript, will be placed in a single separate file. Ingenious!
<h1>Our Application</h1>
<Subscribe></Subscribe>
<main>Some content that spans lots of lines goes here...</main>
<Subscribe></Subscribe>
React takes a rather radical approach and introduces a new language which unifies HTML, CSS and JavaScript: JSX, short for JavaScriptXML. React developers can write their code in JSX and a special compiler called Babel.JS will transform their code back into HTML, CSS and JavaScript which the browsers can parse and display. A more conservative approach would be to use React with plain old JavaScript, but a lot of the benefits that come along with this powerful new language will be lost.
The reactive
part of React comes into play when we bind (connect/sync) specific data to our interface. Whenever this data gets updated, the accompanying DOM elements get automatically updated.
Complete the React Tutorial: An Overview and Walkthrough by Tania Rascia.
Complete the Learn React for free series of interactive screencasts at Scrimba.com
. To complete the course you must spend around 6 to 7 hours watching the screencasts and and about three times this time to practice and write the code yourself and test it on your local enviroment.
Hungry for more React
? Dive into the step-by-step official guide. This course will help you crystalize the fundamental concepts of React and write some more code. Remember: 20% theory, 80% code.
When looking for help, try doing so in the following order:
UPDATED: 29.12.2020
At this point, you should have a deep and nuanced understanding of not just how Javascript works but how you can use it with all the other knowledge you’ve gained so far to build exceptional web applications.
If you find something you don’t know or aren’t quite sure about, you should be a pro by now at Googling your way to an answer, looking at docs, and cruising through Stack Overflow posts. You’ve got all the tools you need to be a developer. And, really, the big secret is that you’ve been a web developer for a long time already.
So where do you go from here? BUILD! Build and build and build and build (see a theme in this curriculum yet?). Use what you’ve learned to create great projects. Get a job so someone else pays you to build. But focus on creating interesting software and using that to drive your education.
There’s a whole world of additional things you can learn — D3 for data visualization, other full-stack frameworks or single-page MVC front-end frameworks… all that stuff is best learned when you’ve got something you want to build that requires "the perfect tool for the job."
And speaking of jobs, if you’ve made it this far then you’ve displayed the kind of capability and drive that employers are looking for. The final step is to show that to the world and get them to pay you to keep learning.
UPDATED: 01.02.2021
Copy your favorite website as well as you can. Pinterest, Facebook, Twitter… Just make sure it’s got lots of interesting functionality. You’ll be integrating your full array of skills into this one….
Of course, you can’t copy every single feature and a lot of the user interface will be a bit clunkier, but you can get yourself 80% of the way there. And that’s darn impressive.
Think about what you’ll need to do to get this all working together. This is where it’s really helpful to think it completely through on paper or whiteboard ahead of time! A few hours of thought here will save you from wasting days of coding. Try to lay it ALL out. An important part of this is scope — you obviously can’t build the entire website (which presumably took a full team of engineers years to produce), so you’ll need to identify the core functionality of the site and then the "nice-to-have" stuff. Make sure you will finish building the core functionality BEFORE starting to add on the rest. If you try to do it all at once, you’ll get lost and frustrated. Trust me. Everything takes longer than you expect.
Build it!
Try testing the very high level Javascript functionality with Jest. Don’t get too bogged down in testing, but try and save yourself time by adding high level tests so you don’t need to click around 100 times every time you make a change to something that seems important.
Once you’ve finished, push to Github’s specified folder and definitely submit your project below!
Good luck!
UPDATED: 01.02.2021
It’s time to really flex your muscles. Test Driven Development can certainly feel uncomfortable at first, but becomes more natural with practice. We’re going to implement the classic game ‘Battleship’. If you’ve never played it, or need a refresher you can read about it here and you can play an online version here.
Since we’re doing TDD, it’s important that you don’t get overwhelmed. Simply take it one step at a time. Write a test, then make it pass.
We have not yet discussed testing the appearance of a webpage. Doing this requires a separate set of tools, and it is outside the scope of this unit. For this assignment do your best to isolate every bit of application functionality from the actual DOM manipulation bits. You can use mocks to make sure that DOM methods like appendChild are being called, but try your best to keep those things outside of the app logic.
Ship
factory function.
hit()
function that takes a number and then marks that position as ‘hit’.isSunk()
should be a function that calculates it based on their length and whether all of their positions are ‘hit’.Gameboard
factory.
receiveAttack
function that takes a pair of coordinates, determines whether or not the attack hit a ship and then sends the ‘hit’ function to the correct ship, or records the coordinates of the missed shot.Player
.
When you finish, create a new branch in the forked exercises repository and submit the Pull Request in the Quiz below.
An important basic concept in testing is isolation. You should only test one method at a time, and your tests for one function should not depend upon an external function behaving correctly – especially if that function is being tested elsewhere. The main reason for this is that when your tests fail, you want to be able to narrow down the cause of this failure as quickly as possible. If you have a test that depends on several functions, it can be hard to tell exactly what is going wrong.
There are many benefits to using Test Driven Debelopment (TDD) when you write your code. One of the biggest benefits is less obvious at first – it helps you to write better code. If you look back at some of your early projects you will probably notice how tightly coupled everything is. All of your functions include references to functions in other parts of your code, and the whole thing is filled with DOM methods or console.log()
.
Tightly coupled code is hard to test! Imagine trying to write tests for a function like this:
function guessingGame() {
const magicNumber = 22;
const guess = prompt('guess a number between 1 and 100!');
if (guess > magicNumber) {
alert('YOUR GUESS IS TOO BIG');
} else if (guess < magicNumber) {
alert('YOUR GUESS IS TOO SMALL');
} else if (guess == magicNumber) {
alert('YOU DID IT! 🎉');
}
}
Making this testable requires us to split up all the different things that are happening. First, we do not need to test the functions prompt
and alert
because they are built in to the browser. They are external to our program and whoever wrote them has already tested them. What we do need to test is the number logic, which is much easier if we untangle it from the other functions:
function evaluateGuess(magicNumber, guess) {
if (guess > magicNumber) {
return 'YOUR GUESS IS TOO BIG';
} else if (guess < magicNumber) {
return 'YOUR GUESS IS TOO SMALL';
} else if (guess == magicNumber) {
return 'YOU DID IT! 🎉';
}
}
function guessingGame() {
const magicNumber = 22;
const guess = prompt('guess a number between 1 and 100!');
const message = evaluateGuess(magicNumber, guess);
alert(message);
}
guessingGame();
In this example, the only thing we really need to test is the evaluateGuess
function, which is much easier to test because it has a clear input and output and doesn’t call any external functions. This implementation is much nicer as well because it’s much easier to extend. If we wanted to switch out the prompt
and alert
s for methods that manipulate the DOM we can do that more simply now and if we want to make our game more advanced by letting the user make multiple guesses, that is also easier.
If we had written this program with TDD it is very likely that it would have looked more like the second example to begin with. Test driven development encourages better program architecture because it encourages you to write Pure Functions.
There are two solutions to the ‘tightly coupled code’ problem. The first, and best option is to simply remove those dependencies from your code as we did above, but that is simply not always possible. The second option is mocking – writing "fake" versions of a function that always behaves exactly how you want. For example, if you’re testing a function that gets information from a DOM input, you really don’t want to have to set up a webpage and dynamically insert something into the input just to run your tests. With a mock function, you could just create a fake version of the input-grabbing function that always returns a specific value and use THAT in your test.
mocking
videos from this series:Too much mocking can be a bad thing. It is sometimes necessary, but if you have to set up an elaborate system of mocks to test any bit of your code, that means your code is too tightly coupled. These two articles (one and two) might be a little extreme, but they contain several really good points about program architecture and testing.
Now that you have some practice and context for TDD, this section of the Jest docs will probably make good sense to you.
Jest includes some really handy mocking functions. Read about them in the official docs
And finally, if you wish, you can add Jest to your webpack setup. Read about that process here.
UPDATED: 01.02.2021
Let’s practice! This testing thing really is not that difficult, but it is quite new. The only way to get comfortable with it is to spend some time doing it.
Write tests for the following functions, and then make the tests pass!
capitalize(string)
takes a string and returns that string with the first character capitalized.
reverseString(string)
takes a string and returns it reversed.
A calculator
object that contains the basic operations: add
, subtract
, divide
, and multiply
.
Caesar Cipher. Read about it on this website and play around with this cool Caesar Cipher Exploration Tool from Khan Academy.
z
to a
.caesar()
function. If it works as expected you can rest assured that your smaller helper functions are doing what they’re supposed to.Array Analysis. Write a function that takes an array of numbers and returns an object with the following properties: average
, min
, max
, and length
.
const object = analyze([1,8,3,4,2,6]);
object == {
average: 4,
min: 1,
max: 8,
length: 6
};
By default, the current version of Jest will not recognize ES6 import statements. In order for you to be able to use ES6 modules for this project you may do the following:
npm i -D @babel/preset-env
{
"presets": ["@babel/preset-env"]
}
This will allow you to use import statements. Note that in the Jest docs a similar instruction is laid out here
UPDATED: 20.01.2021
Test Driven Development is a big deal in the modern development landscape. This is a concept that we introduced way back in our Fundamentals section with our JavaScript Exercises. The main idea is simply that you start working on your code by writing automated tests before writing the code that is being tested. There are tons of benefits to working like this, all of which will be discussed in the resources below.
There are many test-running systems available in JavaScript: Mocha, Jasmine, Tape and Jest to name a few. Fortunately the syntax for each one is very similar. They all have their own set of special features, but the basic syntax is almost identical, so in the end it doesn’t matter which one you use. In fact, simply picking which library to use for this curriculum has been quite tricky!
This lesson is going to center around Jest. The biggest reasons for this decision are that one of the best resources we’ve found for explaining JavaScript testing uses it and they have fantastic documentation. In the end, writing tests is less about the syntax and more about the TDD philosophy. The most important issues are knowing why we write tests and what we test rather than how.
Read this short article that outlines the basic process and the benefits of TDD.
Watch at least the first 3 videos of this video series about testing in JavaScript. The first video focuses heavily on the WHY, while the next two go into more depth about the process. Later videos in the series are definitely worthwhile, but the first 3 are enough to get you up and running.
Read and follow the Getting Started tutorial on the main Jest website.
Read and follow the Using Matchers document on the main Jest website. This one demonstrates some of the other useful functions you can use in your tests.
Watch this amazing next video that covers what to test in your codebase. The video is specifically about testing the Ruby language, but that doesn’t matter at all. The concepts here ring true in any language, and luckily Ruby is a clear enough language that you will be able to follow along just fine. This video might be worth re-visiting after you’ve done some testing of your own.
UPDATED: 19.01.2021
Use everything we’ve been discussing to create a weather forecast site using the weather API from the previous lesson. You should be able to search for a specific location and toggle displaying the data in Fahrenheit or Celsius.
You should change the look of the page based on the data, maybe by changing the color of the background or by adding images that describe the weather. (You could even use the Giphy API to find appropriate weather-related gifs and display them). Feel free to use promises or async/await in your code, though you should try to become comfortable with both.
Set up a blank HTML document with the appropriate links to your JavaScript and CSS files.
Write the functions that hit the API. You’re going to want functions that can take a location and return the weather data for that location. For now, just console.log() the information.
Write the functions that process the JSON data you’re getting from the API and return an object with only the data you require for your app.
Set up a simple form that will let users input their location and will fetch the weather info (still just console.log() it).
Display the information on your webpage!
Add any styling you like!
Optional: add a ‘loading’ component that displays from the time the form is submitted until the information comes back from the API.
Push that baby to github and share your solution below!
Asynchronous code can become difficult to follow when it has a lot of things going on. async
and await
are two keywords that can help make asynchronous read more like synchronous code. This can help code look cleaner while keeping the benefits of asynchronous code.
For example, the two code blocks below do the exact same thing, they both get information from a server, process it, and return a promise.
function getPersonsInfo(name) {
return server.getPeople().then(people => {
return people.find(person => { return person.name === name });
});
}
async function getPersonsInfo(name) {
const people = await server.getPeople();
const person = people.find(person => { return person.name === name });
return person;
}
The second example looks much more like the kind of functions you are used to writing, however, did you notice the async
keyword before the function declaration? How about the await
keyword before server.getPeople()
?
async
function?async
keyword do?await
keyword do?async
function?async
function?async
function?The async
keyword is what lets the javascript engine know that you are declaring an asynchronous function, this is required to use await
inside any function. When a function is declared with async
, it automatically returns a promise, returning in an async
function is the same as resolving a promise, likewise, throwing an error will reject the promise.
An important thing to understand is async
functions are just syntactical sugar for promises
.
The async
keyword can also be used with any of the ways a function can be created, said differently: it is valid to use an async
function anywhere you can use a normal function. Below you will see some examples that may not be intuitive, if you don’t understand them, come back and take a look when you are done with the assignments.
const yourAsyncFunction = async () => {
// do something asynchronously and return a promise
return result;
}
anArray.forEach(async item => {
// do something asynchronously for each item in 'anArray'
// one could also use .map here to return an array of promises to use with 'Promise.all()'
});
server.getPeople().then(async people => {
people.forEach(person => {
// do something asynchronously for each person
});
});
await
is pretty simple: it tells javascript to wait for an asynchronous action to finish before continuing the function. It’s like a ‘pause until done’ keyword. The await
keyword is used to get a value from a function where you would normally use .then()
. Instead of calling .then()
after the asynchronous function, you would simply assign a variable to the result using await
, then you can use the result in your code as you would in your synchronous code.
Handling errors in async
functions is very easy. Promises have the .catch()
method for handling rejected promises, and since async functions just return a promise, you can simply call the function, and append a .catch()
method to the end.
asyncFunctionCall().catch(err => {
console.error(err)
});
But there is another way: the mighty try/catch
block! If you want to handle the error directly inside the async
function, you can use try/catch
just like you would inside synchronous code.
async function getPersonsInfo(name) {
try {
const people = await server.getPeople();
const person = people.find(person => { return person.name === name });
return person;
} catch (error) {
// Handle the error any way you'd like
}
}
Doing this can look messy, but it is a very easy way to handle errors without appending .catch()
after your function calls. How you handle the errors is up to you, and which method you use should be determined by how your code was written. You will get a feel for what needs to be done over time. The assignments will also help you understand how to handle your errors.
Remember the Giphy API practice project? (If not, you should go back and complete the API lesson) We are going to convert the promise based code into async/await
compatible code. Here’s a refresher of the code we are starting with:
<script>
const img = document.querySelector('img');
fetch('https://api.giphy.com/v1/gifs/translate?api_key=YOUR_KEY_HERE&s=cats', {mode: 'cors'})
.then(function(response) {
return response.json();
})
.then(function(response) {
img.src = response.data.images.original.url;
});
</script>
Since await
does not work on the global scope, we will have to create an async
function that wraps our API call to Giphy.
<script>
const img = document.querySelector('img');
async function getCats() {
fetch('https://api.giphy.com/v1/gifs/translate?api_key=YOUR_KEY_HERE&s=cats', {mode: 'cors'})
.then(function(response) {
return response.json();
})
.then(function(response) {
img.src = response.data.images.original.url;
})
}
</script>
Now that we have a function that is asynchronous, we can then start refactoring from using promises to using await
:
<script>
const img = document.querySelector('img');
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=YOUR_KEY_HERE&s=cats', {mode: 'cors'});
response.json().then(function(response) {
img.src = response.data.images.original.url;
});
}
</script>
Since response
is still the same object we have passed to the .then()
block at the start, we still need to use the .json()
method, which in turn returns a promise. Because .json()
returns a promise, we can use await
to assign the response to a variable.
<script>
const img = document.querySelector('img');
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=YOUR_KEY_HERE&s=cats', {mode: 'cors'});
const catData = await response.json();
img.src = catData.data.images.original.url;
}
</script>
To use this function, we just simply need to call it with getCats()
in our code.
<script>
const img = document.querySelector('img');
async function getCats() {
const response = await fetch('https://api.giphy.com/v1/gifs/translate?api_key=YOUR_KEY_HERE&s=cats', {mode: 'cors'});
const catData = await response.json();
img.src = catData.data.images.original.url;
}
getCats();
</script>
This code will behave exactly like the code from the last lesson, it just looks a bit different after refactoring. async/await
are very useful tools when it comes to cleaning up asynchronous javascript code. It is important to remember async/await
are just promises written in a different way. Do the assignments below, and dive deeper into the understanding of async/await
.
Read this article for a solid introduction to async/await. this article also has some good examples of it’s use.
Read this article for a more in-depth look at async/await, including how to handle errors.
Watch the next video for a good overview on async/await and it’s purpose, along with a special trick.
UPDATED: 19.01.2021