Coming Soon: Real Talk Podcast

By John Papa

Coming Soon: Real Talk Podcast

Remember that time you had that bug that too took you an all-nighter to solve? And that time when you first saw hot-reloading work and it saved you tons of time when making sure your website looked right?

We all have real life development stories we tell each other about the good and bad struggles we faced, and how we ultimately came to overcome them. Often these experiences define why we choose to use the technologies that we use today. We think it would be great to share these stories with everyone.

Real Talk JavaScript

We’re excited to announce we’ve created a new podcast titled Real Talk JavaScript. It will be on all the major podcast channels starting October 2, 2018 and then every Tuesday morning! You can follow us at @realtalkjs on Twitter for announcements.

Coming Soon: Real Talk Podcast

Here is the key theme you will hear on the podcast:

real developers talking to other real developers about real applications they’ve built and why they chose the technologies.

Simply put, Real Talk JavaScript is a weekly podcast where you can hear about the challenges facing Web developers today while expert guests on the show share their experience solving concrete problems while building real Web applications.

Along with my co-hosts, Ward Bell and Dan Wahlin, we’ll dive into JavaScript and Web development stories for practical insights and honest talk about the topics you are facing today.

Asking Why

There are plenty of great shows about ideas and architectures and new products. We love those shows. We’re doing something different. We’re digging into the techniques and technologies we use, solving challenges many of us have. We think it’s good to ask “why”. Why did we choose a technology to solve this problem we face? Did it go well? Did it go poorly? What did you learn? What was the journey like and what advice would you share with someone following your footsteps?

We’re focusing on concrete experiences. While we will absolutely center around great technologies like Angular, Vue, React, Node.js and more, we’ll invite our guests to talk about specific problems they’ve encountered and how they addressed those problems with the tools and techniques.

We think that many of you want to hear these stories and can likely recognize yourselves being in similar situations!

The Topics and Flow

Want a sneak peek into how the show till flow? Here’s an example Ward wrote.

Imagine you were on the show to talk about Dependency Injection (that’s native to Angular but you could be talking about DI in react or vue … or why react or vue doesn’t need it in your opinion).

You might begin like this:

“I and many others want to handle Http calls the same way no matter where they are in the component hierarchy. Just the other day I was looking at our app and each component was calling http directly. Each component handled its own errors (or not) and did so in its own way. Each added headers it’s own way. Each handled results its own way.

Every component did it differently. This was a big project, expected to last years. We were building a team for the long haul. People would come and go. Consistency would matter, both in training new people and crushing bugs. Yet, even today, with the code fresh in our minds, no one could predict how a component would get its data. We also found that testing the components was hard because we spent so much time mocking http calls. And our components were full of stuff that didn’t have anything to do with presentation. That made them bigger and harder to understand then they needed to be.

Dependency Injection helped us out of our hole. We pulled all that Http code out into separate service classes that we inject into the component class constructors.

It took us about a week to sweep the code base. And here’s what happened.”

From such a beginning, together we can explore probing questions:

  • Didn’t that double the number of classes you had to manage? Did that bother you?
  • How did you make sure that the services themselves were consistent … or did that just move the consistency problem somewhere else?
  • What if you hadn’t used DI? Could you have achieved the same result some other way? Maybe with redux/ngrx/vuex/mobx/suspense?
  • Would you do it again? Slightly differently?
  • How did the team respond? How did you convince them to do it? Was there resistance? How
    did you overcome that (if you did)?

This type of flow focuses on “why” and the experience, while also allowing us to share what technologies can help us all with everyday Web development. This means our topics can be about great platforms and frameworks like Node.js, Angular, React and Vue, but also about tools like VS Code or WebPack, or docker, cloud solutions, AI and ML, mobile, testing, or pretty much anything that touches Web development.

Community

The Web community has amazingly generous and kind people who share. Many of us receive help along the way. We believe paying it forward is the right thing to do. This is why we also share, at the end of our show, “someone to follow”. This can be anyone our guests feel should be shared more widely in a nod to the community that helps us all.

We’ll kick things off with a mailbag question from some of you. We’ll use social media to gather questions for our guests and read and answer some of them on air.

We love the Web and we know so many other people do too. We hope you enjoy hearing these stories of Web developers, their struggles, their successes, and the tools that they use.

Welcome to Real World JavaScript!

John, Ward, and Dan

Source:: johnpapa

​All My JavaScript is Broken and I Don't Know Why

By Sentry

There are few things in life that I enjoy more than good, healthy, broken code. It’s inevitable that things are going to break, it’s inevitable that I’m going to need to debug those things, and it’s inevitable that I’ll need do whatever is necessary to fix them. No one ever ships 100% perfect code.

This happens all the time: we ship code to production, all our tests pass, things seem fine, we celebrate… and then users start complaining. Sometimes they complain right away. Sometimes days later. We usually have no idea what happened to make them complain in the first place. No one has ever intended their code to unexpectedly break whatever it broke.

So we end up scrambling to do post-mortem debugging. An exception has happened, we don’t have the info as to why, but we need to figure it all out real quick by debugging after the fact.

But we want to catch these issues before users have the chance to complain to us. Ideally, this would be solved easily with tests. Why not just cover every scenario with a test? Then life would be perfect and fine and great.

Why Not Tests?

Because here in reality, humans are pretty bad at writing tests. Not just because we’re all kinda lazy and maybe a little dumb, but also because:

– Who wants to write tests for everything?

If your product has a customer base and one of those customers emails you to complain about something being broken, they probably send you a message like: “It doesn’t work for me. Please fix! I’m losing revenue.” People are always losing revenue, even if your app just hosts cool pictures of dogs.

If you’re fortunate enough to hear from a tech savvy user, then you can maybe somehow convince them to open up their browser console, reproduce the bug, and send you a screenshot. If an exception happens in production and nobody sees the Chrome debug console, did it really happen?

You probably won’t be so fortunate. Which may lead you to throw up your hands. “It works for me and I’m not going to fix this cause I don’t know how to debug your problem. And I’m not getting enough info to fix.”

Why Not Rely on Users?

Obviously we don’t want to rely on users sending angry messages and faulty screenshots to tell us what happened. We want to see what happened in real time. We want to see the stack trace and the problem in context. How can we be more proactive about this?

Well, there’s always the most obvious way to go about doing this, my absolute old time favorite: a window.onerror.

If you’re not familiar, it’s essentially a global callback that throws a net over your entire application. I call it window.onNOPE. It’s literally the worst way to capture an exception other than mind melding with your code so that it makes you faint every time it breaks.

The callback signature used to look something like this:

function(message, url, lineNumber)

It took three arguments, the first one being a message, the url of the file that caused the exception, and the lineNumber

The problem here is that none of these are an actual Error object. They’re just a message, url, and a number. In practice these three arguments end up looking like this:

message: "TypeError: Cannot read property 'foo' of undefined" 
url: "http://example.com/foo.js"
lineNumber: 10

At a glance this looks really useful. We can drill into our code, look at line 10, and figure out what’s going on. The issue is that your code is probably minified. Line 1 is your entire application. You have a million characters on this one really (really) really long line.

Also, your JS Is likely hosted on another domain. A CDN or a subdomain or a cookie-less domain, something like that. If a script is on another domain, it’s subject to CORS (Cross Origin Resource Sharing). And if the page it’s on doesn’t have the proper CORS headers — and it probably doesn’t — then all window.onerror is gonna tell you is “Script Error”. So you have literally no idea what happened, just that something happened. It’s like if someone called the fire department to alert them there was a fire somewhere in a thousand mile radius and that they really need to get on that.

Over time browsers have expanded on window.onerror to include more information:

function(message, url, lineNumber, columnNumber, error)

Now we have our Error object. This is nice, cause we can (try to) get a stack trace from this. For those unaware (though you are almost certainly already very much aware), a stack trace is just a record of the function calls up to this point within the current call stack. A series of function calls: you call a, a calls b, b calls c, and on down the call stack.

When you’re debugging something, if you don’t have a stack trace it’s going to be very difficult to fix. You can maybe see that the exception happened at this line, but you don’t know how you actually got there: you don’t know which function called that function; you don’t know the order of events that preceded it.

Let’s explore by opening up our favorite executable to throw a new error:

$ node 
> throw new Error('lol')

I’m sure you’ve seen something like this:

Error: lol
    at repl:1:7
    at REPLServer.self.eval (repl.js.110:21) 
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12) 
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10) 
    at Interface._line (readline.js:531:8) 
    at Interface._ttyWrite (readline.js:760:14) 
    at ReadStream.onkeypress (readline.js:99:10)

This is what comes back when you arbitrarily throw and do not catch an exception. What do each of these things mean?

It gives us the caller, aka the function of the frame (Interface.EventEmitter.emit). The source the function was called in (events.js). The line number (95). And the column number (17).

We also now have this property off the error prototype “.stack”. A string. Probably the most useless thing you can get back from this.

If you want to start breaking this apart and extract the pieces out of it, you need to use a regular expression, something like:

/at (?:(.+)s+)?(?(?:(.+?):(d+)|([^)]+)))?/

What’s this look like in practice? Great question. And something we’ll dive into in our next edition of All My Javascript is Broken and I Don’t Know Why.

We’re Here to Help.

As always, you can try Sentry for your JavaScript app (or an app written in virtually any other language too). We’re 100% open source and we’ll give you all the details you need so you don’t have to worry about the above.

Now get out there and break some code.

Source:: scotch.io

Destructuring Assignment In JavaScript

By Chris Nwamba

I’m not so sure, but I think JavaScript might be the only web technology where you can destructure objects and assign the individual units in one take. It is also one great feature that allows you can get straight to the point with what you have to do and keep things very clean.

Destructuring assignment in more simple words means unpacking the values of objects or arrays into simple variables. You have probably already seen it used somewhere, and it never made sense to you. At the end of this guide, we will see how to use it and what it can replace for you.

Prerequisites

Let’s Start With Arrays

Old school ways tell us that if we have an array and we want to assign some of it’s values to variables, we do something like this:

let johnDoe = ["John", "Doe", "Iskolo"]
let firstName = johnDoe[0]
let lastName = johnDoe[1]
let title = johnDoe[2]

console.log(firstName, lastName, title) // John Doe Iskolo

But would you not like to do this instead?

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe
console.log(firstName, lastName, title) // John Doe Iskolo

The best part is that you can pick any number of elements you want

let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName] = johnDoe
console.log(firstName, lastName) // John Doe

Or

let johnDoe = ["John", "Doe", "Iskolo"]
let [, lastName, title] = johnDoe
console.log(lastName, title) // Doe Iskolo

We can do it with strings as well

let [firstName, ,title] = "John Doe Iskolo".split(" ")
console.log(firstName, title) // John Iskolo

We can throw in the rest operator to collect the rest 😆

let [firstName, ...others] = "John Doe Iskolo".split(" ")
console.log(firstName, others) // John Iskolo

And we can even bring in objects here

let johnDone = {}
[johnDoe.first, johnDoe.last] = "John Doe Iskolo".split(" ")
console.log(johnDoe.first, johnDoe.last) // John Doe

In Looping Through Objects
We can use it in looping through a key-value pair variable like an object or map. Here is what is very common:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
Object.keys(obj).forEach(key => {
  console.log(`${key} : ${obj[key]}`)
})

We can spin that differently like this:

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}
for(let [key, value] of Object.entries(obj)) {
  console.log(`${key} : ${value}`)
}

It might look like the same thing to you, but it is not. In using forEach above, we pull the keys of the object into an array, then looping through that array of keys now and using those keys to pick out the values of objects. Phew! I lost my breath for a second reading that 😃.

In the second part, we just go straight and loop through each object entries and extracting the keys and values.

Assigning default values
We can assign defaults values, just for a situation where the variable we wish to destructure is empty

let [firstName = "John", ,title = "Fire"] = "John Doe".split(" ")
console.log(firstName, title) // John Fire

Now To Objects

Like we did with arrays, we can destructure objects as well. If you have ever used React, you are likely to have seen this used when importing a module.

let obj = {
  firstName : "John",
  lastName : "Doe",
  title : "Iskolo"
}

let {firstName, lastName) = obj
console.log(firstName, lastName) // John Doe

When destructuring objects, we use the keys as variable names. This is how JavaScript knows which property of the object you want to assign. Unlike arrays where you use their index/positions in the assignment, here you use the keys.

This destructuring works on any kind of object. If your object has nested values, you can still destructure that and extract the values into variables.

let obj = {
  name : "John Doe",
  address : {
    city : "Omsk",
    country : "Russia"
  }
}
let {city, country} = obj.address
console.log(city, country) // Omsk Russia

Using It To Pass Function Arguments

Let’s be frank, you might have seen functions that look like this:

function sumFunc(a = true, b = "", c = "", d = 0, e = false) {
  console.log(a,b,c,d,e)
}
// Call the function
sumFunc(true, "", "", "", true)
// Or if we want to preserve default values
sumFunc(true, undefined, undefined, undefined, true)

It doesn’t look so good. It gets worse if you are trying to perform a function like making a chart and you need a lot of arguments (think like 15 optional arguments) to create the chat. It is plainly unsustainable.

Let destructuring save the day 😃

function sumFunc({a = true, b = "", c = "", d = 0, e = false}) {
  console.log(a,b,c,d,e)
}
let args = {a : false, e: true}
// Call the function
sumFunc(args)

By passing the function arguments as an object, they will get automatically resolved into independent arguments. Now, we pass an object with matching key-value pairs and the function will work nicely.

Admit it, you love the destructured way 😁.

Conclusion

Destructuring is an operation you can do without, however, you can already see how it makes you a better developer. Cleaner code, fewer repetitions and more structure over what you have.

Use destructuring today and make your code a better code 😀.

Source:: scotch.io

How monday.com makes project management AWESOME for web developers

By Nicholas Cerminara

Monday.com Demo

So what the heck is monday.com? You’re probably see a bunch of promotions for it.

Every project management tool seeks to do the same instrumental thing: keep teams connected, on task and on deadline to get major initiatives done.

But the market is getting pretty crowded, and for good reason — no platform seems to have gotten the right feel for what people need to see, and how that information should be displayed so that it’s both actionable/relevant, and contextualized.

Introduction

That’s why monday.com is worth a shot. The platform is based off a simple, but powerful idea: that as humans, we like to feel like we’re contributing to part of a greater/effort good — an idea that sometimes gets lost in the shuffle as we focus on the details of getting stuff done.

So projects are put onto a task board (think of it like a digital whiteboard), where everyone can have the same level of visibility into anyone else who’s contributing set of tasks. That transparency breaks down the silos between teams that cause communication errors and costly project mistakes — and it’s a beautiful, simple way to connect people to the processes that drive forward big business initiatives.

Clean Design

Whether you’re part of a tech-forward team or not, monday.com is a welcome relief to cumbersome Excel files, messy (physical) whiteboards, or meetings that waste time when actual work could be completed.

The scalable, intuitive structure can effectively work for a team of two, or an international team of 2,000+ — and a beautiful, color-coded board lays out tasks you can cleanly see and tag for various stages of completion. That way, employees can see exactly what needs to be done (and who needs to do it), while managers can optimize their time re-allocating resources as necessary to optimize processes. It’s a win-win.

Team Focused

monday.com also allows teams to communicate within the platform, cutting down on the amount of laborious sifting through various email threads to figure out a workflow. Messages can be sent inside of tasks — so all the communication is contextualized before meeting resolution or seeking it.

The platform also supports uploads, so documents and videos can be added to facilitate more collaboration, and integration with other productivity apps. So if your team is already using tools like Slack, Google Calendar, Dropbox, Microsoft Excel, Trello, and Jira, there’s specific, clean shortcuts to integrate the information from those platforms into monday.com. And even beyond team communication and management, you can use monday.com for client-facing exchanges, so all your messages are consolidated into a single place.

Conclusion

The platform recently raised $50M in funding, and received nods from the likes of Forbes, Entrepreneur, Business Insider, and more for its ability to empower international teams to do better work together. Best of all, unlike other team management software, which can be pricey and time-intensive to scope, test and run, you can try monday.com today — for free.

See if monday.com is the right fit for your team: create your free account and start using the platform today.

This post is sponsored.

Source:: scotch.io

Building a React Native app as a Designer using BuilderX

By BuilderX

BuilderX Launch Screen

BuilderX is a screen design tool that codes React Native* for you. It generates beautiful, readable and editable code for the designs. Just design the components in your app, or import your Sketch file and it generates the corresponding code. You can hop between design and code with just a click owing to the amazing bi-directional flow in BuilderX.

The Problem

It’s 2018, and Designers and Developers still don’t speak the same language. There is still a huge gap between the Design and Development phase. Designers and Developers work on different workspaces, tools, and most importantly, file formats. BuilderX is a revolutionary tool that seamlessly bridges this gap.

First, you will need to install BuilderX. Just go to builderx.io and install BuilderX.

BuilderX Interface

BuilderX workspace is majorly divided in five sections:

  • Artboard – Artboard corresponds to a screen in your app. This is where you design awesome stuff.
  • Toolbar – The toolbar on the top contains some basic tools for your design like Shapes, Text, Images, etc. and also some useful actions like create group and create symbol.
  • Properties Panel – Properties panel on the right lets you adjust the properties of the selected layers and artboard.
  • Left Panel – The left panel contains Layers and Symbols list. The layer list shows all the layers in your current Artboard. Symbols panel contains pre-built components as well as your project’s symbols that you can drag and use.
  • Code Editor – Code editor is useful for developers as it lets you make changes in your code directly and changes will be reflected in real-time.

Creating the App

In this tutorial, we will be creating a Hacker News App clone using BuilderX to design our components and then integrate the API calls with code generated to fetch the data in real-time and run the app on the device. First, we will create a new project from the BuilderX launch screen.

On creating a new project, you see the project screen where the Artboard is shown in the centre as described in the previous section.
BuilderX Workspace

This is where we create our components. We will be saving the project as HackerNews-BuilderX.

First, let’s create a rect and give it a color, which in code would correspond to component in React Native.
<img data-src="https://cdn.scotch.io/68403/nMy76KsBStGoVsk1Y3Ux_creating-rect.gif" alt="Draw a Component”>

Then, to create a header, we will insert some icons by using icon menu in top toolbar. After inserting the icon, we change it to menu icon. Similarly, we can design the whole header. By using flex or different alignments, we can adjust the icons in the header.
<img data-src="https://cdn.scotch.io/68403/3PotRTXSVWGpK1OgoEUF_Creating-Icon.gif" alt="Design a

Component”>

After designing the header, we can convert it to symbol so that we can use it on
other screens as well without having to re-create it.
Make Symbol

Next, we will create a list item component that we will be using to show a single news-item. It would contain three text components inside a rect on the left and a rect on the right that would show number of comments and score. Clicking on it would navigate to screen.
Create a list-item component

After creating the list-item, we can directly create a list of that component that would correspond to the in React Native.
Create a list from list-item component

After this, we will add Footer in our screen. For this,we will use predefined Material Footer symbol from BuilderX symbol library.
<img data-src="https://cdn.scotch.io/68403/NmMTiFKeRvmihGsBojCa_Adding-footer.gif" alt="Add a

component”>

Notice that we can also customise the symbol as needed and override the icons and texts.
Now, we will create a new Screen for comments page. Also, if we have similar design for the new page then we can just duplicate the previously created screen or we can re-use the symbols. Here, we will use the Card component from BuilderX symbol library and modify it to fit our requirements.
Add card component for comments section

We can can also always change the design from the code and changes will be reflected in real-time.
Design & Code Simultaneously

After designing the comment component, we will create a list like in previous screen and make it a FlatList. Currently, our design will work for almost all mobile screens with few exceptions like iPhoneX or other phones with notch. BuilderX conditionals takes care of that for us. You can change the screen specific design by recording conditions for that screen.
Conditionals in BuilderX

After we have designed the app, it looks like this.
Final design of HackerNews clone

Now, we will move to the next phase of adding business logic to our code.

Adding business logic to the App

In this phase, we open the component files in an editor and add the functions to fetch the data from the API. We will add this code snippet to our LandingPage.js inside class.

constructor() {
    super();
    this.state = {
      newsList: []
    };
    this.fetchData = this.fetchData.bind(this);
  }
  componentDidMount() {
    this.fetchData();
  }
  async fetchData() {
    const response = await fetch(
      "https://hacker-news.firebaseio.com/v0/topstories.json"
    );
    const data = await response.json();
    this.setState({ newsList: data });
  }

After adding code and mapping the state to the components, we get these screens.
Business logic integration

Similarly, we will add these functions and mappings with respective API end-point in all screens. We also need to pass props while navigating between screens. The ListItem component now looks something like this in code.

async fetchData() {
    let url =
      "https://hacker-news.firebaseio.com/v0/item/" + this.props.id + ".json";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ news: data });
  }
  render() {
    return (
      <View style={[this.props.style]}>
        <View style={styles.itemContainer}>
          <Text style={styles.itemName} numberOfLines={2} ellipsizeMode="tail">
            {this.state.news.title ? this.state.news.title : "Title"}
          </Text>
          <Text style={styles.itemAuthor}>
            {this.state.news.by ? this.state.news.by : "User"}
          </Text>
          <Text style={styles.itemUrl} numberOfLines={2} ellipsizeMode="tail">
            {this.state.news.url ? this.state.news.url : "Text Added"}
          </Text>
        </View>
        <TouchableOpacity
          style={styles.button}
          onPress={() => {
            this.props.navigation.push("CommentsPage", {
              commentsList:
                this.state.news && this.state.news.kids
                  ? this.state.news.kids
                  : [],
              title:
                this.state.news && this.state.news.title
                  ? this.state.news.title
                  : "",
              url:
                this.state.news && this.state.news.url
                  ? this.state.news.url
                  : ""
            });
          }}
        >
          <View style={styles.commentsContainer}>
            <Svg style={styles.ellipse} viewBox="0 0 100 100">
              <Ellipse
                rx={50}
                ry={50}
                cx={50}
                cy={50}
                fill="rgba(249,205,175,1)"
              />
            </Svg>
            <Text style={styles.commentNumbers}>
              {this.state.news.kids ? this.state.news.kids.length : "106"}
            </Text>
          </View>
          <View style={styles.upvotesContainer}>
            <Text style={styles.upvotes}>
              {this.state.news.score ? this.state.news.score : "151"}
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }

Running code on device

After integrating the code and the business logic, we will run the app on our device.
Preview on simulator

Conclusion

This was just a simple app. But you can design and code fairly complex apps using BuilderX. Using BuilderX, developers can be sure to save at least 50% of their time, and iterate faster on ideas.
Another amazing thing to note here is that design changes in the app can be made even after the app is shipped without having to reiterate the development phase.

You can check the complete code here on the github repo.

Quick Links

You can also follow BuilderX on Facebook and Twitter to stay updated with the latest news.

* more tech to follow

Source:: scotch.io

Announcing Scotch v8! Our Biggest Upgrade Ever

By Chris Sevilleja

Scotch.io v8

I’ve been waiting to write this post for a very very very long time. Work on this v8 site started in February of this year. This is version 8 in the 4.5 years we’ve been in existence.

Rebuilding Scotch has always been a fun project for me. Getting to try all the latest and greatest toys in a site. Aside from trying new toys though, here’s the main reasons I decided to start another new site:

Site speed was slow for international users

Since our servers live in New York, we saw site loading speeds of 5-10 seconds. For international users however, they were seeing a 20+ second load time. Unacceptable!

Finding content was difficult

We now have over 400+ guest authors. We were often publishing these amazing articles and then seeing them get buried down the feed. On top of that, our site search didn’t surface the right content.

Our main nav in the previous site only had three links in it to find content. People didn’t even know we had three major sections for:

  • Guides: Think docs for specific technologies
  • Courses: Videos to build real-world projects
  • Posts: Written tutorials

Better author tools for coding tutorials

Our previous editor was old school. A combination of textarea, wysiwyg, and some JavaScript. I’ve learned a fair amount about writing coding tutorials and think that the tools for writing these should be better. More on this in the coming months, but this new site was meant to be a foundation for all those cool new things coming.

Those were the three big reasons for jumping to another redesign. This v8 will be the foundation for Scotch moving forward and I swear I’m done redesigning. If I start to try, somebody take away my keyboard.

Major Features

These are the features I’m most excited about:

Speed! Speed! Speed!

Performance is a feature. With Google using site speed as a ranking factor, this was very important now more than ever. Using SpeedCurve, we can see the differences between old site and new site.

SpeedCurve comparisons

I did a writeup on How We’re Getting to 1s Speeds. TLDR: We are fully caching the HTML of our pages and serving globally using Cloudflare.

I’ll be doing a whole guide on web performance soon, but here’s the gist of what we did technically:

  • Fully cache entire HTML
  • Auth moved to JavaScript (React) and JWTs
  • Responsive and optimized images with Cloudinary
  • Multiple lazy-loaded JS files with webpack

We moved closer to a JAM stack type setup without completely moving to a JAM stack setup. v8 is JAMstack-ish! There’s all this great work happening around static sites generated with tools like Gatsby and Hugo. We can have that fun too and cache our entire site.

Backend is still Laravel. Frontend is React. All API communication between the two using JWTs.

Pages fully cached by Cloudflare

Cloudflare is a brilliant service that helped us grow Scotch from a tiny Digital Ocean box to what we are today. Up until now, we’ve had Cloudflare only cache assets like images/js/css.

A BIG performance boost can be found in letting Cloudflare cache your entire siteincluding the HTML.

This effectively means that Cloudflare can serve HTML directly to your users without having to hit your server.
By turning on full page cache through Cloudflare, we’ve been able to save server usage. We may even get to downgrade our servers and save some dough.

A caveat for doing full page cache through Cloudflare’s page rules is that all your authentication has to be done via client-side JavaScript. If you handle authentication server side, then an authenticated page may be served to future users that aren’t authenticated. This is similar to how you would handle authentication in a single page app.

Real-time search everywhere

We had worked on a little real-time search in v7. It was only on our /tutorials page though. In v8, real-time search courtesy of Algolia is everywhere. Give it a try!
undefined

  • The header search bar
  • The home page
  • Courses and Posts pages

Please excuse the ugly gif color representation

And the header search:

Better Discoverability

With the new header and also real-time search, I’m hoping that readers can find more of what they need. A good exercise is:

Try finding your favorite Scotch post and see if it comes up!

The header also has links to popular tags and sections of Scotch. I’m hoping the nav let’s people see that we have more than just the written tutorials. More to be added soon!

New Dashboard

The new dashboard is found at https://my.scotch.io and is fully a React SPA. The dashboard was moved out of the main site repo and into it’s own repo.

The new dashboard is authenticated using JWTs and powered by the Laravel API.

It is hosted on Netlify, which is an awesome tool if you are looking to host any Single Page Apps. It was between Netlify and zeit’s now service which is also awesome.

New Writing Tools

With the help of genius Samuel Oloruntoba (@kayandrae07), we’ve been able to build out a new editor that is far more modern than our last one.

The goal is to have the best writing experience and tools for coding tutorials.

This is the foundation of our new editor and we’ll be adding more to this in the coming weeks. Here’s a couple things we’re looking at

Writing Templates

A lot of posts that you want to write will have the same foundations. I’m also sprinkling in my favorite best practices for writing each type of post. Coming soon.

A Better Video Experience

Our courses and videos have gotten a big redesign to be much simpler to click around.

Playlist on the right side just like you’d expect from any of the viewing sites.

Conclusion and Future

Moving forward, I think we’ve landed on a good foundation for all the goals we have for the coming year. Let me know in the comments what you think. Is the site fast for you? Can you find what you’re looking for?

Here’s some things I’m looking to add in the coming weeks:

  • Learning Guides. Everything you need to learn a language/library/project in one centralized location
  • Post Ideas: Submit and vote on what posts you’d like to see written next
  • Job Board
  • Cool Stuff: I get asked a lot what kind of tools I use, I’ll write it all here

Bonus

I’m super stoked to have this tiny feature. Hover over the logo in the top left for the animated logo made by Luis Manuel (@lmgonzalves)!

Source:: scotch.io

Build Your First App with React's Context API

By redbmk

One of React’s latest features is the Context API. Up until now, Context within React has been somewhat experimental, but still used in quite a few popular libraries, like Redux and React Router. There are plenty of ways to avoid using Context, but sometimes it can be really useful.

One really good use case for Context is keeping track of authentication. In fact, React’s official documentation for the Context API mentions it can be used for authentication.

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

The examples in their documentation are helpful, but they don’t actually include an example of sharing the authenticated user. I’ll show you here how one way to use the new Context API to simply keep track of whether a user is authenticated, and some basic profile information.

React Context in a Nutshell

Before going too far down the rabbit hole, let me give you a quick introduction into the Context API. As of React version 16, React ships with a function called createContext that takes a single value parameter. Calling createContext gives you both a Provider and Consumer component.

You can render the Provider component anywhere in your app – in multiple places if you like. If there is a Consumer anywhere inside the Provider (even deeply nested somewhere), it will have access to that value parameter in the form of a render function as a child. Each Provider can also override the value. For example:

import { createContext } from 'react';

const { Provider, Consumer } = createContext('default value');

export default () =>
  <main>
    <Provider>
      <Consumer>{value => <span>{value}</span>}</Consumer>
    </Provider>
    <Provider value="overridden value">
      <div>
        <Consumer>{value => <span>{value}</span>}</Consumer>
      </div>
    </Provider>
  </main>
);

Will render the following:

<main>
  <span>default value</span>
  </div>
    <span>overridden value</span>
  </div>
</main>

Because Provider is just a component, you can easily create a wrapper component that passes its state into the value prop of the Provider. Then you will have access to that component’s state anywhere in the app via the Consumer. In this tutorial, I’ll show you how to use one component to keep track of auth state changes and pass that information down via the Context API.

Build a Simple React App

The quickest way to get started with React in my experience is using the official Create React App CLI. It bootstraps an app for you giving you some decent defaults. To use it, install it globally with NPM, then run it with the name of your app as a parameter. This will create a new folder with everything you need to get started, and will even install the dependencies for you. You can then run the app using yarn start.

npm install --global create-react-app@1.5.2 yarn@1.7.0
create-react-app react-context
cd react-context
yarn start

You should now be able to see your app running by visiting http://localhost:3000 with your browser.

For this tutorial, I’ll show you how you can take advantage of the new Context API to cut down some of the boilerplate that is often paired with authentication. Before getting started with Context, you’ll need to set up authentication in order to tie it in.

Create an Okta Application

One simple way to add authentication to your project is with Okta. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

If you don’t already have one, sign up for a forever-free developer account. Log in to your developer console, navigate to Applications, then click Add Application. Select SinglePage App, then click Next.

Since Create React App runs on port 3000 by default, you should add that as a Base URI and Login Redirect URI. Your settings should look like the following:

Click Done to save your app, then copy your Client ID and paste it as a variable into a file called .env.local in the root of your project. This will allow you to access the file in your code without needing to store credentials in source control. You’ll also need to add your organization URL (without the -admin suffix). Environment variables (other than NODE_ENV) need to start with REACT_APP_ in order for Create React App to read them, so the file should end up looking like this:

.env.local

REACT_APP_OKTA_CLIENT_ID={yourClientId}
REACT_APP_OKTA_ORG_URL=https://{yourOktaDomain}

The easiest way to add authentication with Okta is to use Okta’s React SDK. You’ll also need to add routes, which can be done using React Router. I’ll also have you start adding icons to the app (for now as an avatar icon to show you’re logged in).

yarn add @okta/okta-react@1.0.3 react-router-dom@4.3.1

For routes to work properly using React Router, you need to wrap your whole application in a router (for the web, you need to use BrowserRouter). Similarly, to allow access to authentication anywhere in the app, you need to wrap the app in a Security component provided by Okta. Okta also needs access to the router, so the Security component should be nested inside the router. You should modify your src/index.js file to look like the following:

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Security } from '@okta/okta-react';

import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const oktaConfig = {
  issuer: `${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default`,
  redirect_uri: `${window.location.origin}/implicit/callback`,
  client_id: process.env.REACT_APP_OKTA_CLIENT_ID,
};

ReactDOM.render(
  <BrowserRouter>
    <Security {...oktaConfig}>
      <App />
    </Security>
  </BrowserRouter>,
  document.getElementById('root'),
);

registerServiceWorker();

Now in src/App.js you can use Routes that tell the app to only render a certain component if the current URL matches the given path. You can also use Links to create a link to that route (or page) and properly modify the browser’s history to work in a single-page app.

Go ahead and create a nav tag with links to the Home page (/) and a Profile page (/profile). Also, create a main tag containing your routes. For now just stub in some inline components that render the name of the page.

By using Okta’s SecureRoute you will find that whenever you try to go to that page you will need to be logged in. If you’re not currently logged in, you’ll be redirected to /implicit/callback to log in. In order for that route to actually log you in, you also need to create a route that renders Okta’s ImplicitCallback component.

src/App.js

--- a/src/App.js
+++ b/src/App.js
@@ -1,4 +1,7 @@
 import React, { Component } from 'react';
+import { Link, Route } from 'react-router-dom';
+import { SecureRoute, ImplicitCallback } from '@okta/okta-react';
+
 import logo from './logo.svg';
 import './App.css';

@@ -9,10 +12,16 @@ class App extends Component {
         <header className="App-header">
           <img src={logo} className="App-logo" alt="logo" />
           <h1 className="App-title">Welcome to React</h1>
+          <nav className="App-nav">
+            <Link to="/">Home</Link>
+            <Link to="/profile">Profile</Link>
+          </nav>
         </header>
-        <p className="App-intro">
-          To get started, edit <code>src/App.js</code> and save to reload.
-        </p>
+        <main className="App-intro">
+          <Route exact path="/" component={() => 'Home Page'} />
+          <SecureRoute exact path="/profile" component={() => 'Profile page'} />
+          <Route path="/implicit/callback" component={ImplicitCallback} />
+        </main>
       </div>
     );
   }

Note: You can apply a diff in git by copying it to a file and using the git apply command. If you’re following along this avoids having to write the file out manually. For example, if you save the above as a file named app.diff, then from your project folder, you could type git apply app.diff and it should apply those changes.

To make this look a little nicer, add a bit of CSS to let the header expand to the content, give the main part of the app some padding, and make the nav links a bit more readable.

src/App.css

--- a/src/App.css
+++ b/src/App.css
@@ -9,17 +9,35 @@

 .App-header {
   background-color: #222;
-  height: 150px;
+  min-height: 150px;
   padding: 20px;
   color: white;
 }

+.App-nav {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+.App-nav a {
+  color: white;
+  padding: 0 5px;
+  text-decoration: none;
+  cursor: pointer;
+}
+
+.App-nav a:hover {
+  text-decoration: underline;
+}
+
 .App-title {
   font-size: 1.5em;
 }

 .App-intro {
   font-size: large;
+  margin: 1em;
 }

You should now have a slightly modified version of the default page from Create React App that says “Home page”. You should also now be able to click on the Profile link and you will be prompted to log in to your account. Upon success, you’ll be taken to the profile page, that at the moment just says Profile page.

Note: You may need to restart the development server after adding the environment variables. You can do this by going to the terminal running the server and hitting ctrlc, then re-running the yarn start command.

Home page

Add a User Greeting with React Context

Using React’s new Context API, you can create a component that you will use to wrap your entire application, similar to the way BrowserRouter or Security works. Once that Provider is in place, you can access pieces of authentication anywhere in the application without a lot of boilerplate.

In this case, create a context using createContext. You’ll then check when the component is first mounted, and again whenever it updates, if the user is authenticated. If this is different from the current state, then it also checks for the user and saves that as well. The reason the state is only updated whenever the authentication is different from the previous state is that otherwise, the componentDidUpdate function would trigger another update, sending this component into an infinite render loop.

To keep this simple to use, the default export is the Context’s Consumer. The Provider component is exported separately and is wrapped with Okta’s withAuth to give it access to the auth prop.

Note: Checking authentication during componentDidUpdate is admittedly not the most efficient method. At the time of this writing, there is not a simple way to detect when the state of authorization changes, so this is a simple approach for demo purposes. This example might not work well for larger applications.

src/Auth.js

import React, { createContext, Component } from 'react';
import { withAuth } from '@okta/okta-react';

const AuthContext = createContext({
  user: null,
  isAuthenticated: null,
});

export default AuthContext.Consumer;

class AuthController extends Component {
  state = {
    user: null,
    isAuthenticated: null,
  }

  componentDidUpdate() {
    this.checkAuthentication();
  }

  componentDidMount() {
    this.checkAuthentication();
  }

  async checkAuthentication() {
    const isAuthenticated = await this.props.auth.isAuthenticated();
    if (isAuthenticated !== this.state.isAuthenticated) {
      const user = await this.props.auth.getUser();
      this.setState({ isAuthenticated, user });
    }
  }

  render() {
    return (
      <AuthContext.Provider value={this.state}>
        {this.props.children}
      </AuthContext.Provider>
    );
  }
}

export const AuthProvider = withAuth(AuthController);

The app’s main entry point now needs to be wrapped in the AuthProvider. It needs to be inside Security so that it can access the auth using withAuth.

src/index.js

--- a/src/index.js
+++ b/src/index.js
@@ -6,6 +6,7 @@ import { Security } from '@okta/okta-react';
 import './index.css';
 import App from './App';
 import registerServiceWorker from './registerServiceWorker';
+import { AuthProvider } from './Auth';

 const oktaConfig = {
   issuer: `${process.env.REACT_APP_OKTA_ORG_URL}/oauth2/default`,
@@ -16,7 +17,9 @@ const oktaConfig = {
 ReactDOM.render(
   <BrowserRouter>
     <Security {...oktaConfig}>
-      <App />
+      <AuthProvider>
+        <App />
+      </AuthProvider>
     </Security>
   </BrowserRouter>,
   document.getElementById('root')

Now that the Context Provider is set up and ready to go, you can start using the Consumer. For a quick example, try changing the homepage to greet the user when they’re logged in. If they aren’t logged in, keep the old message of Welcome to React.

React Contexts take a render function as its child element. The parameters passed in are going to be the state of the provider (the data passed into value). Because of this, to access the user, you need to pass in a function that expects an object containing the key user. If this is null then authentication is still loading. If it’s undefined then the user is not authenticated. Otherwise, it will contain the user’s basic profile information. Go ahead and ignore the loading state for now, and only greet the user once you have their information.

src/App.js
``diff
— a/src/App.js
+++ b/src/App.js
@@ -5,13 +5,21 @@ import { SecureRoute, ImplicitCallback } from ‘@okta/okta-react’;
import logo from ‘./logo.svg’;
import ‘./App.css’;

+import Auth from ‘./Auth’;
+
+const welcomeUser = ({ user }) => user

  • ? Welcome, ${user.given_name || user.name}!
  • : ‘Welcome to React’;
  • class App extends Component {
    render() {
    return (

    logo

  • Welcome to React

  • {welcomeUser}
  • Logged in greeting

    Create a Login/Logout Link

    A pretty common scenario with authentication is having a button or link that you can click to log you in when you’re authenticated. You can use the same React Context to determine whether or not a user is logged in.

    In order to properly log the user in or out when they click the link, you can wrap the component with withAuth to get access to the login and logout functions of auth.

    This time, you don’t want the user to click either Login or Logout if you’re not sure what the state of authentication is yet. You could implement some sort of loading icon here, but for this demo just render nothing until you know whether or not the user is logged in.

    src/LoginButton.js

    import React from 'react';
    import { withAuth } from '@okta/okta-react';
    
    import Auth from './Auth';
    
    export default withAuth(({ auth }) => (
      <Auth>
        {({ isAuthenticated }) => {
          if (isAuthenticated === null) return null;
    
          return (
            <a onClick={() => isAuthenticated ? auth.logout() : auth.login()}>
              {isAuthenticated ? 'Logout' : 'Login'}
            </a>
          );
        }}
      </Auth>
    ));

    Now you can add the Login/Logout link to your list of nav items:

    src/App.js

    --- a/src/App.js
    +++ b/src/App.js
    @@ -6,6 +6,7 @@ import logo from './logo.svg';
     import './App.css';
    
     import Auth from './Auth';
    +import LoginButton from './LoginButton';
    
     const welcomeUser = ({ user }) => user
       ? `Welcome, ${user.given_name || user.name}!`
    @@ -23,6 +24,7 @@ class App extends Component {
               <nav className="App-nav">
                 <Link to="/">Home</Link>
                 <Link to="/profile">Profile</Link>
    +            <LoginButton />
               </nav>
             </header>
             <main className="App-intro">

    Homepage with Login button

    Homepage with Logout button

    Create a Real Profile Page

    From the user value in your Context, you can also now get access to the user’s basic profile information.

    Semantically, a dl HTML tag is a “Description List” element. This is a good, basic way to display metadata. However, you’ll probably want to add a little bit of simple styling. This will make sure the text isn’t center-aligned, and make the term (the dt tag) bold. Create a new file Profile.css that you’ll import in your profile page.

    src/Profile.css

    dl {
      text-align: left;
    }
    
    dt {
      padding: 4px 0;
      font-weight: bold;
    }

    Lodash provides a suite of utilities to manipulate data. To keep things simple and automated, try using that to convert the name of a key to something more personable. The startCase function will convert a string like given_name to Given Name. To add Lodash as a dependency, run the following:

    yarn add lodash@4.17.10

    The updated_at key is actually just a number representing the number of seconds from 1970, so you can convert that to a human-readable string in JavaScript using new Date(updated_at * 1000).toString().

    Putting all that together, you can create a functional component that takes a user prop, and wrap that in the Auth Context Consumer. This time, show a simple loading message if the user isn’t loaded yet. Technically, the user will be undefined if authentication finished and there is no user, but because this is in a SecureRoute, if there is no user then the page will redirect to the home page.

    src/Profile.js

    import React, { Fragment } from 'react';
    import { startCase } from 'lodash';
    
    import Auth from './Auth';
    import './Profile.css';
    
    const ProfilePage = ({ user }) => {
      if (!user) return 'Loading...';
    
      return (
        <dl>
          {Object.keys(user).sort().map(key => (
            <Fragment key={key}>
              <dt>{startCase(key)}</dt>
              <dd>{key === 'updated_at' ? new Date(user[key] * 1000).toString() : user[key]}</dd>
            </Fragment>
          ))}
        </dl>
      );
    }
    
    export default () => <Auth>{ProfilePage}</Auth>;

    In your app’s routes, replace the mock profile page with a reference to the real one you just created:

    ``diff
    — a/src/App.js
    +++ b/src/App.js
    @@ -7,6 +7,7 @@ import ‘./App.css’;

    import Auth from ‘./Auth’;
    import LoginButton from ‘./LoginButton’;
    +import ProfilePage from ‘./Profile’;

    const welcomeUser = ({ user }) => user
    ? Welcome, ${user.given_name || user.name}!
    @@ -29,7 +30,7 @@ class App extends Component {

    ‘Home Page’} />
    – ‘Profile page’} />
    +

       </div>
    
    
    Now when you go to the profile page, you get some details about the logged in user.
    
    ![complete-profile-page.png](https://res.cloudinary.com/scotch/image/upload/v1535753116/qd7zqx6jjjr2zjyenxcw.png)
    
    ## Learn More About React and Authentication with Okta
    
    I hope I've given you a better understanding of React's new Context API and how it can be useful for cutting down on boilerplate or sharing simple pieces of application state. For more information and example on the Context API, check out [React's documentation](https://reactjs.org/docs/context.html). For more examples using React with Okta, check out some of these posts or browse the [Okta Developer Blog](https://developer.okta.com/blog/).
    
    * [Build a Health Tracking App with React, GraphQL, and User Authentication](https://developer.okta.com/blog/2018/07/11/build-react-graphql-api-user-authentication)
    * [Tutorial: Build a Secure CRUD App with Symfony and React](https://developer.okta.com/blog/2018/08/23/symfony-react-php-crud-app)
    * [Add Okta authentication to your React App](https://developer.okta.com/code/react/)
    * [Build User Registration with Node, React, and Okta](https://developer.okta.com/blog/2018/02/06/build-user-registration-with-node-react-and-okta)
    
    And as always, we'd love to hear from you. Hit us up with questions or feedback in the comments, or on Twitter [@oktadev](https://twitter.com/oktadev).

Source:: scotch.io

Debugging Create React App Applications in Visual Studio Code

By James Quick

Learn VS Code

In this post, we are going to create an Create React App application, then add configuration to debug it in Visual Studio Code.

Watch on YouTube

TLDR – For an Create React App application, install the Debugger for Chrome extension, create a debug configuration in VS Code, and then run in debug mode.

Learn VS Code

If you’re interested in learning more about VS Code, you definitely want to check out the upcoming Learn VS Code course.

Creating a Starter Project

To be able to test an Create React App application, you need an Create React App application 🙂 I’ll provide the basic steps, but for more reference on how to get started look at the Create React App page.

First, you’ll need to install the Create React App.

npm install -g create-react-app

After that finishes, you’ll need to actually generate your new application. This will take a bit as it needs to install LOTS of NPM packages.

create-react-app my-app

Open the project in VS Code and you should see the following.

Create React App Project in VS Code

Now, that you’ve got your new fancy React app, go ahead and run it to make sure everything looks right.

npm start

Should look like this.

Create React App Project Running

Creating Debug Configuration

Assuming you’ve made it this far, we are ready to start debugging! Before we do, however, it’s worth understanding how configuring debugging in VS Code works. Basically debug configurations are saved in a launch.json file which is stored inside of a .vscode folder. This .vscode folder is used to store different configurations for Code including our required debugging stuff.

Before you create your debug configuration, you need to install the Debugger for Chrome extension. Find and install this extension from the extension tab in VS Code. After installing, reload VS Code.

Debugger for Chrome

Now, to create a debug configuration, you can open the debug panel (the bug looking button on the left panel). At the top of the debug panel, you should see a dropdown that says “No Configurations”.

Create Debug Configurations

To the right of that dropdown, there is a gear icon. Click this button to have VS Code automatically generate that .vscode folder and launch.json file mentioned above.

Then choose Chrome.

Choose Chrome Debug Configuration

You should get the following configuration created for you.

Create React App Debug Configuration

The only thing we need to do is update the port from 8080 to 3000.

Updated Create React App Debug Configuration

Let’s Debug

Now we’re ready! Go ahead and click the play button at the top of the Debug panel which will launch an instance of Chrome in debug mode. Keep in mind your app should already be running from using ng serve earlier. In VS Code, you should see the Debug toolbar pop up.

With this up and running, you can set a breakpoint in your App.js. Open up your App.js and add a breakpoint inside of the render function by clicking in the gutter (to the left of the line numbers). Should look like this.

Now, refresh debugging by clicking the refresh button on the debugging toolbar. This should open your application again and trigger this breakpoin. You should be directed back to VS Code directly to the place where you set your breakpoint.

From here, you can set more breakpoints, inspect variables, etc. If you are interested in learning more about debugging JavaScript in general in either Chrome or VS Code you can check out Debugging JavaScript in Chrome and Visual Studio Code.

Again, if you’re interested in learning more about VS Code, you’ll definitely want to check out the upcoming Learn VS Code course.

If you have any follow up questions or comments, leave one below of find me on twitter @jamesqquick.

For video content, check out my YouTube Channel

Source:: scotch.io