Friday Picks 078

Here are five resources for this weekend: The Big List of 101 Places to Learn to Code for Free: tons of free resources Build and Deploy a Full Stack MERN Project - React + Redux, Node, Express, MongoDB [Part 1/2]: complete app tutorial in 2 parts Some “cool” machine learning books: a list of machine-learning books, might be of interest Next.js 101 - Free Online Course: short mini-course on Next.
Read more →

Black Friday Deals 2020

Here are the tech-related Black Friday Deals for 2020. HTML/CSS https://debuggingcss.com/ JavaScript/Node/React/Vue https://flaviocopes.com/blackfriday/ https://jamstackhandbook.com/ https://learnetto.com/blackfriday#Pricing https://nodecli.com https://react2025.com/ https://wesbos.com/courses https://www.leveluptutorials.com/ https://www.udemy.com/course/nestjs-zero-to-hero/?couponCode=DD074A391845400CC7E7 https://www.vuemastery.com/black-friday-2020/ Go https://buildsaasappingo.com https://lets-go.alexedwards.net https://www.calhoun.io/ Flutter https://codewithandrea.com/courses/ Domains/Hosting https://www.namecheap.com/ Python https://training.talkpython.fm/black-friday-2020 Elixir https://pragmaticstudio.com/ https://alchemist.camp/subscribe/level-up Ruby https://pragmaticstudio.com/ Misc Mastering Vim Quickly Standard Edition | Professional Training Package | Premium Training Package https://appbrewery.com/ https://deals.bytesized.xyz/ https://keleshev.com/compiling-to-assembly-from-scratch/ https://media.
Read more →

Friday Picks 077

Read more →

Friday Picks 075

Read more →

Friday Picks 073

Read more →

Friday Picks 072

Read more →

4 TILS from the Epic React Basic React Hooks Workshop

What did I learn from the workshop Basic React Hooks by Kent C. Dodds? Previously, I wrote down my learnings from the React Fundamentals workshop. The second workshop introduces React hooks. Here are some insights that I found useful: Set Initial State Via Props Set an initial value by adding props to a component: <Greeting initialName="George"> Take that as an argument to the function and pass it down to useState:
Read more →

Friday Picks 071

Read more →

3 TILs from the Epic React Fundamentals Workshop

Kent C. Dodds released his Epic React training course with a big fanfare last week. I was on the fence of buying this, as the pro license is a premium training course that comes with a premium price tag. The course is expensive compared to other online courses. For example, a year-long-subscription to Frontend Masters costs roughly the same. But as a life-long learner, I’m dedicated to becoming a better programmer.
Read more →

Heroku React Express Content Security Policy With Stripe, Cloudinary and Google Fonts

How to fix “Refused to connect to xxx because it violates the following Content Security Policy directive” on Heroku I’ve deployed a MERN stack app to Heroku: Mongo DB, Express.js, React.js, Node.js. The app uses Google Fonts and Stripe Checkout. I’ve built the React app via Create React App. My last deploy went wonkers. The app didn’t load any JavaScript because of Content-Security-Policy failures. In this post I’ll show you how to fix those errors and how to successfully re-deploy your MERN app to Heroku.
Read more →

Friday Picks 067

Read more →

Friday Picks 066

Here are some links for this weekend. I hope you’ll enjoy them! Full Stack Serverless - Building a Real-time Chat App with GraphQL, CDK, AppSync, and React: a concise tutorial by Nader Dabit Build A Confirmation Modal in React with State Machines: learn more about state machines with Dave Ceddia Building Microservices with Deno, Reno, and PostgreSQL: by James Wright Show your latest dev.to posts automatically on your GitHub profile readme: a GitHub action that automatically fetches blog posts from dev.
Read more →

Friday Picks 064

Here are some resources for you: Testing React Apps: a guide for testing React applications with the Jest framework How to Code in Go: free ebook for learning Go How to get started with the 11ty (Eleventy) Blog Starter: a tutorial on using Eleventy and Sanity.io (a content management system) Your First Tailwind Website: a YouTube video on using TailWind CSS Node Auth Tutorial (JWT): a video series on authentication with Node.
Read more →

Friday Picks 063

Read more →

Friday Picks 056

Read more →

Friday Picks 055

Read more →

Static File Server With Deno and Abc

Let’s say I have some static files I want to serve. For example, a React app or a Svelte app. Create Svelte App Let’s use the Svelte template: npx degit sveltejs/template svelte-app cd svelte-app npm install Now we need to create a production build: npm run build The command will create an optimized build in the public folder. Create Deno Server Install Deno. We’ll use the third-party module Abc to create a simple web server.
Read more →

Friday Picks 052

Read more →

Tuesday Picks 005

Read more →

Friday Picks 051

Read more →

Tuesday Picks 004

Read more →

Friday Picks 050

Here are some links: Code Tetris: JavaScript Tutorial for Beginners - learn the basics of JavaScript by coding a Tetris game from scratch Beginner’s Guide to React w/ Hooks (2020) Free Course - a 2-hour free YouTube video by popular instructor Colt Steele Go GraphQL: Introduction to building GraphQL API in Golang #1 - a multi-part tutorial series Design Resources For Developers - a curated list of free design and UI resources by Brad Traversy [AskJS] Has anyone used GraphQL for a large project and regretted it?
Read more →

Snagged Some Udemy Courses on Sale May 2020

Read more →

Tuesday Picks 003

Read more →

Tuesday Picks 002

Read more →

Friday Picks 048

Read more →

Friday Picks 047

Read more →

Friday Picks 046

Read more →

Friday Picks 045

Read more →

More Learning Resources During COVID-19 Outbreak Part 3

Read more →

Friday Picks 040

Read more →

Friday Picks 036

Read more →

Friday Picks 035

Read more →

Friday Picks 034

Read more →

Friday Picks 032

Read more →

Test Redirect With Jest, React-Router and React-Testing-Library

You’ve set up react-testing-library with Jest and react-router. You want to check that a component successfully redirects to another page. But how? Your React application comes with a protected route. If a user is not authenticated, the app should redirect the user to the login screen. You’ve managed to set up react-router-dom for your component. For example, here’s an excerpt from a UserStatus.jsx component that only an authenticated user should be able to access:
Read more →

Month of Testdriven Python and React

Read more →

Example Multi Stage Docker Build for React

I’m still trying to improve my Docker builds. Here’s an example for a multi-stage Docker build for React:

base imageFROMnode:12.13.1-alpine as compile-image## install global packagesENV NPM_CONFIG_PREFIX=/home/node/.npm-globalRUN npm install npm@latest -gRUN npm install pnpm react-scripts@3.3.0 -g## set working directory & give permissions to user nodeRUN mkdir -p /usr/src/app && chown node:node /usr/src/appWORKDIR/usr/src/app## switch to non-root user & install dependenciesUSERnodeCOPY package*.json /usr/src/app/COPY pnpm-lock.yaml /usr/src/app/pnpm-lock.yamlENV PATH /usr/src/app/node_modules/.bin:$PATHENV PATH=$PATH:/home/node/.npm-global/binRUN pnpm install## set environment to production, overwrite## with docker-composeARG NODE_ENV=production ENV NODE_ENV $NODE_ENV## create buildCOPY .

Read more →

Fix Import React Renderer With Jest Error

A few days ago, I updated a React application that uses Jest and Enzyme for testing. The new tests yielded errors like cannot find module ‘react-test-renderer’. Solution: Install react-test-renderer and enzyme-to-json as dev dependencies, and re-factor tests to use enzyme-to-json. npm i –save-dev react-test-renderer enzyme-to-json In your package.json file, add the serializer to your jest config: { "jest": { "snapshotSerializers": [ "enzyme-to-json/serializer" ] } } Example test file before update:
Read more →

Learning About Best Practices for Docker and Node

Today I’ve tried to update one of my Docker apps that uses React, Enzyme, and Jest. This lead me on a wild goose chase about react-test-renderer and best practices for Docker builds for Node.js. I’m still not sure where the problem is (Enzyme, maybe?). But I found three useful resources for Docker and Node.js: Docker and Node.js Best Practices Node + Docker Hello World, for Showing Good Defaults for Using Node.
Read more →

Friday Picks 028

Read more →

Decked Out With Black Friday Swag

Read more →

Black Friday Deals 2019

Here are some sweet Black Friday Deals. Wes Bos Wes Bos creates high-quality courses about JavaScript and React. Now all of those courses are on sale. I bought the FullStack Advanced React & GraphQL course. Wes glosses over some concepts, but overall the quality is quite high, and the course was well worth the money. Find an overview over all courses at wesbos.com/courses. Talk Python The Mega-Bundle Deal is $50 off: $149 for the whole course catalog.
Read more →

Friday Picks 026

Here are some useful links for you: Colors And Fonts: a curated library for front-end developers and designers RxJS with React Hooks for state management: a beginner-friendly tutorial Barebones AWS Amplify + React + GraphQL App: get started quickly with this tutorial Building a payments system with React and Stripe: this tutorial shows you how to use Stripe in your React.js application React, Redux and JavaScript architecture: a post from 2018 that’s still helpful in understanding the basic concept of Reat.
Read more →

First Thoughts About ReasonML vs TypeScript

Today I finished my first TypeScript experiment with React. Here are some thoughts after using ReasonReact first, and now TypeScript second. Setup Is Not Better Than ReasonReact I used Create React App to bootstrap the app. npx create-react-app <project-name> –typescript But then I had to setup ESLint and Prettier with TypeScript. ReasonML & BuckleScript: npm install -g bs-platform bsb -init <project-name> -theme react-hooks After that you’re done. It’s JavaScript
Read more →

Preparing For My First Tech Talk: TypeScript Experiments

A few days ago I started preparing for my first tech talk. One of the common questions about ReasonML and ReasonReact is: Why not TypeScript? If you’re looking for a statically typed alternative for JavaScript, TypeScript seems like the obvious choice. I did a TypeScript workshop with FrontEnd Masters (online) a while ago, but I have to admit that I didn’t use TypeScript in practice. The last few days I started creating a simple TypeScript React app.
Read more →

Avoid Memory Leak With React SetState On An Unmounted Component

Raise your hand ✋, if you’ve seen this error in your React application: Warning: Can’t call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. The Problem This error often happens when you make an asynchronous request for data, but the component unmounts. For example, some logic in your app tells React to navigate away from the component.
Read more →

Gatsby Build Times On Netlify Solved?

I wrote about my Gatsby build time woes yesterday. Unfortunately, Netlify and Gatsby rebuild my site completely with every update. I use the gatsby-plugin-netlify-cache but build times are still high. While searching for ways to optimize my Netlify build I stumbled upon an issue on the Gatsby repository. The issue was merged into master and published to gatsby@2.17.0. Before: At the moment this hash changes if anything within ./src has changed between builds.
Read more →

Gatsby Builds Take A Long Time

When I started the blog, I wanted a quick solution that simply works. That’s why I’m using a Gatsby Starter. I didn’t want to fiddle around with my blog too much. I chose Gatsby because it’s build with JavaScript and React.js. There are other candidates like Hugo, but I’m not familiar with the programming language it’s built with (Golang). Gatsby offers great features out of the box, and it was easy to deploy to Netlify.
Read more →

Thinking in React Hooks

I’m a big fan of Dave Ceddia’s blog for bite-sized overviews of React Hooks. For example, the articles A Simple Intro to React Hooks or How the useContext Hook Works are excellent short introductions to a complex topic. Yesterday, I found this gem: Thinking in React Hooks The article compares class-based React components to React hooks in a concise, and visually appealing way. I recommend checking out the article, even if you’re already familiar with React hooks.
Read more →

Beginner Error with (Reason)React And Updating State

A few weeks ago, I started learning ReasonML and ReasonReact. After doing a basic tutorial, I decided to tackle a form with validation. Building a simple form is not too hard, but it offers some interesting challenges. Some examples include getting user input and storing it locally, adding validation logic, and displaying the validation messages. Thus Reason Form was born. It takes inspiration from James King’s Using Custom React Hooks to Simplify Forms and a (deprecated) course about TDD with React, Flask, and Docker.
Read more →

Working On Stale State And Hooks

Learning the fundamentals of React was reasonably straightforward. React.js adds a lot of abstraction over JavaScript. But after you’ve got the basic building blocks down, you can get quite far. You can profit from the vast ecosystem, and the tons of available material (tutorials, StackOverflow, blog posts, etc.). But the more you work with state, props, you realize that there are a lot of pitfalls. You probably don’t need derived state, but sometimes you do.
Read more →

State Management is Hard

State management in React.js and ReasonReact proves to be challenging. I have two pieces of state with useReducer, which I can’t get synchronized. Another problem is to conditionally setup useReducer depending on a prop. It probably results from a limitation of ReasonReact because Reason is stricter than JavaScript. It keeps being exciting to learn new things. Addendum: Kent C. Dodds wrote an excellent blog post about this topic today: Don’t Sync State.
Read more →

Sale: Microservices with Docker, React, Flask

I started the Microservices with Docker, Flask, and React a while ago. The course proved to be quite challenging, as I’m not familiar with Docker and Flask. It also uses advanced features of React. It was very fascinating for me to see how to develop a modern application with TDD, using Docker. While the React part is a bit outdated (it still uses deprecated methods like getDerivedState) - everything works and teaches you useful concepts.
Read more →

ReasonReact is Still React

The problem with ReasonReact is - it’s still React. (No kidding.) Today I tried fixing a bug in my ReasonReact form app. After some debugging, I realized that I have a problem with derived state which I receive from a custom hook. I now have to find out how to best synchronize my state. The good thing about ReasonReact is - it’s still React. Easily search for solutions, and utilize your previous React knowledge.
Read more →

Format And Fix All Files With Prettier And ESLint (Recursively)

The problem: You have a bunch of JavaScript and .jsx files that you wish to parse with Prettier and ESLint. Why? You would like to make sure that ESLint analyzes your code for problematic patterns. You would like to have consistent formatting, and don’t worry about code style while writing the code. In this post, I’ll show you how to recursively fix and format all your JavaScript files with one command.
Read more →

Friday Picks 018

Read more →

ReasonReact Pause

In the last few days, I’ve been working hard on learning ReasonReact by creating a small project. I’ve learned a lot, but it has been quite frustrating, too. At the moment, I’m trying to set up form validation logic. ReasonReact is giving me the stink eye. I recently bought the book Learn Type-Driven Development by Yawar Amin. He is a helpful member of the community and seems to know his stuff.
Read more →

Learning ReasonReact Step by Step: First Thoughts

The last few days, I’ve spent a lot of time learning ReasonReact. It has been a frustratingexperience so far. Even simple tasks like creating forms prove to be quite hard for me. I’m quite familiar with React. Of course, I’m no expert by far. But I can use the new Hooks API, useReducer, useContext, etc. With ReasonReact, even easy tasks get more complicated. You have to learn how to use the type system with the ReasonReact API.
Read more →

Learning ReasonReact Step by Step Part: 1

Let’s continue from yesterday’s post and build the skeleton for our application: a simple form with ReasonReact and hooks. Go to the src folder. The main App.re file should just render a Form component: [@react.component] let make = () => <Form />; The syntax looks unfamiliar. What is [@react.component]? It is a decorator attribute and tells ReasonReact that you’re writing a React component. Duh! The latest ReasonReact version uses React hooks under the hood.
Read more →

Working on ReasonReact, Svelte and React

I’m currently working on three different toy apps/learning projects: a Meetup clone in Svelte.js, an online store in React (with Redux, GraphlQL, etc.), and a simple todo with ReasonReact. It’s interesting to see how different framework tackle state management, UI rendering and the complexity of front-end development. So far, I’ve found Svelte the easiest to grasp. React has the best documentation and the best ecosystem. ReasonReact is functional (OCaml with React bindings under the hood) and typed.
Read more →

Why Try ReasonReact?

In the last few days, I’ve taken a look at Reason. I’m interested in ReasonReact as an alternative to using JavaScript on the front-end. I enjoy the style and patterns of functional programming languages. While I can write vanilla JavaScript in a functional style, it’s very brittle. If you want to have immutable data structures, and better library support for a functional style, you have to shove in a ton of libraries like Immutable.
Read more →

Taking a Look at ReasonML And ReasonReact

Last weekend I took a peek at Reason, a JavaScript-like-syntax for OCaml. Ocaml is a multi-paradigm language from 1996 which also supports a functional programming approach. It is also typed and compiled. Reason is an alternative syntax and toolchain for OCaml with better JavaScript interop and convenience features (via BuckleScript, the compiler). Reason also has pattern-matching. When I first learned Elixir, I was blown away by the power of pattern-matching. I’m happy to see that Reason offers it, too.
Read more →

React Render Props and Svelte Slots

I’m trying to wrap my head around React’s render props and Svelte’s slots. Not much to write here, I still try to understand how it works. State Management in SPAs is quite complicated. There are a lot of solutions: passing props down, the Context API, the new useContext hook, state management libraries like Redux or MobX, state machines, etc. But you can also use component composition by rendering the children props.
Read more →

Learning About React Context

I’m expanding my React knowledge so that I can build better apps. One of my learning resources is the Udemy course Complete React Developer in 2019 (w/ Redux, Hooks, GraphQL). I’ve been familiar with the basic setup of React’s Context API. But there are some nuances, of course. Below are some blog posts to get you started on the topic. Further Reading How the useContext Hook Works by Dave Ceddia Redux vs.
Read more →

Learning About React and Derived State

Read more →

Docker NGinx 405 POST Not Allowed

Today it took me over one hour to debug an error with Docker and Nginx. Every time I tried to submit a form with a POST method, NGinx gave me a 405 error: “405 Not Allowed”. I originally thought that Nginx overrode React Router settings and tried to troubleshoot my production NGinx config. StackOverflow had some ideas: POST request not allowed - 405 Not Allowed - nginx, even with headers included.
Read more →

Still Learning TDD

Read more →

Permission Denied When Installing NPM Packages With Docker

I have the following Dockerfile for a React app:

base image FROM node:11.12.0-alpine ## set working directory WORKDIR /usr/src/app ## add /usr/src/app/node_modules/.bin to $PATH ENV PATH /usr/src/app/node_modules/.bin:$PATH ## install and cache app dependencies COPY package.json /usr/src/app/package.json COPY package-lock.json /usr/src/app/package-lock.json RUN npm install react-scripts@3.0.1 -g –silent RUN chown -R node:node . USER node RUN npm ci ## start app CMD ["npm", "start"] After setting up the work directory I copy the package.

Read more →

Friday Picks 013

Read more →

MicroServices with Docker, Flask, and React

Today I reviewed my progress with the Microservices with Docker, Flask, and React by Michael Herman. I’m not familiar with Flask, but I wanted to learn how to build a microservices app with TDD. The testdriven.io course was the best course I could find which uses Docker, and React and teaches testing principles. The parts about Docker proved already useful. I used the setup to dockerize a simple Django app.
Read more →

Learn About Gatsby Themes

Yesterday I finished Introduction to Gatsby, a beginners course by Jason Lengstorf, hosted by Frontend Masters. Gatsby is a static site generator for JavaScript/React.js. It pre-builds your website and serves static images. Thus, it’s very fast. But it can also load dynamic data because it also is a fully fledged React app. The Gatsby team just released a big feature: Gatsby Themes. Gatsby Themes are similar to Wordpress plugins. They are pre-configured and you can load them into your Gatsby configuration.
Read more →

Learning About State Management

Today I listened to a React Podcast episode where Michel Weststrate was a guest. He talked about state management, MobX, and Immer, his new library. Listening to talk like these, and the ideas behind JavaScript libraries and software architecture make me insanely happy. I’m excited about learning such concepts and how they play out in web development. It’s also humbling to realize how much I still don’t know. I’ve been thinking about how to build and structure a front-end React app.
Read more →

React.js & Node.js App Deployment with Heroku

Read more →

Friday Picks 008

Here are some things I’ve found useful this week or that I enjoyed: TypeScript Weekly - a newsletter for TypeScript How YOU can use Nest to build a GraphQL API - a tutorial that walks you through building a GraphQL endpoint with CRUD functionality Forget about component lifecycles and start thinking in effects - about React Hooks Build a Todo App in React Using Hooks - simple tutorial for beginners One simple trick to optimize React re-renders - without using React.
Read more →

Simple Frontend Pagination in React

Read more →

React.js - How to Fetch Data

Read more →

Friday Picks 007

Here are some things I’ve found useful this week or that I enjoyed: You don’t need passport.js - Guide to node.js authentication - Santiago Quinteros explains how authentication in Node.js applications work Implementing DTOs, Mappers & the Repository Pattern using the Sequelize ORM [with Examples] - DDD w/ TypeScript - how to handle data access with TypeScript and Domain-Driven Design What’s the best documentation you’ve ever seen? - reddit thread: I like the DigitalOcean Tutorials Using Typescript in Node.
Read more →

TIL: How to Pass Props to React Router

Just a short note: Today I learned that you shouldn’t pass props to React Router with the component attribute, but with render. From the Docs: When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component.
Read more →

Writing Ugly React.js and GraphQL

At the moment, I’m going through Reed Barger’s course Serverless React with AWS Amplify - The Complete Guide. I’m learning a lot about serverless JavaScript/React development with AWS. But wow, does it get ugly. Code duplication, wrangling with the AWS back end, fetching data several times, etc. I don’t have a lot of confidence in AWS Amplify. It makes it relatively easy to create a back-end API with GraphQL. But the documentation is lacking, the AWS web console confusing, and the pricing (after the free trial months) steep.
Read more →

Custom React Hook: Use AWS Amplify Auth

AWS Amplify offers an Authentication API that allows you to manage and store users. Here is an example for a custom React Hook with useReducer and useEffect that fetches the current user data from AWS Amplify: import { useReducer, useState, useEffect } from 'react' import { Auth, Hub } from 'aws-amplify' const amplifyAuthReducer = (state, action) => { switch (action.type) { case 'FETCH_USER_DATA_INIT': return { …state, isLoading: true, isError: false, } case 'FETCH_USER_DATA_SUCCESS': return { .
Read more →

React Components

You can do a lot of nifty things with React when you think about how you can use functions in JavaScript. At the moment, I’m learning more about reusable components and composing components together. When I see these patterns, I always think: “Of course, it’s function composition” - but I would never have come up with this pattern on my own. Luckily, there are great teachers that can help me with that:
Read more →

Friday Picks 002

Read more →

Free React Function Component Workshop

Read more →

UIx — Experimental ClojureScript Wrapper for Modern React.js

Read more →

Friday Picks 001

Read more →

Focus on JavaScript

I’ve decided to dial back my interests and to focus on JavaScript/React.js, front-end tech, and clean code/architecture. Maybe I’ll throw in some ClojureScript… Work has picked up and I have limited time I can spend on coding. Although I love Elixir and functional programming languages, it will be better to double down on one tech stack - for now. JavaScript is beginner-friendly and offers tons of tutorials and other material for a web-dev newbie.
Read more →

React useEffect Bug

I’ve spent tons of hours trying to understand how the React Hook useEffect works and how I can avoid memory leaks. At this point, my best guess is that it’s a bug. Related issues: setState hook inside useEffect can cause unavoidable warning Can’t perform a React state update #14369 setState in useEffect causing a “React state update on an unmounted component” warning #15057 In my case, I created a custom Hook that interfaces with the GraphQL endpoint and pulls data with useEffect.
Read more →

Persistence

I’m still trying to figure out what causes a memory leak with my useEffect custom React Hook. I read tons of articles (I recommend Dan Abramov’s) but I haven’t found the solution. My custom data fetching hook (with an asynchronous API call) messes with state although the component is unmounted. The obvious solution is to add a cleanup function. But my implementation (see “Abort Data Fetching in Effect Hook” from this article) doesn’t work.
Read more →

React Hooks: useEffect Cleanup

Currently I’m wrangling with cleaning up my data fetching functions with useEffect. I return a function that React can run when it unmounts, see React Documentation. In my example, I use the didCancel Boolean from this article. Unfortunately, it doesn’t work and still fetches data even if I navigate away from the page that uses the custom data fetching hook. import { useEffect, useReducer } from "react"; import { API, graphqlOperation } from "aws-amplify"; import { getMarket } from ".
Read more →

Learning More About React Hooks

I’m extensively using React Hooks. There are new patterns to learn and some pitfalls to avoid. Here are some good resources that help with learning more about Hooks: A Simple Intro to React Hooks by Dave Ceddia How to Use the useReducer Hook by Dave Ceddia How the useEffect Hook Works by Dave Ceddia How the useContext Hook Works by Dave Ceddia Application State Management with React by Kent C.
Read more →

React useState Hook

I’m now writing my React apps with Hooks. I’m accustomed to the way setState() worked: state updates may be asynchronous and updates were merged. That’s why I used functions instead of objects when calling setState(). Doing so ensured that you always get the newest values. Example: this.state = { person: { firstName: "", secondName: "" } }; this.setState(prevState => ({ person: { …prevState.person, firstName: "Tom", secondName: "Jerry" } })); The useState Hook works differently.
Read more →

My Favorite Front End Web Podcasts

Read more →

Assertion failed: Input argument is not an HTMLInputElement

I have a form input text field and press the enter key to submit the form. I get an error “Assertion failed: Input argument is not an HTMLInputElement”. Assertion failed: Input argument is not an HTMLInputElement getFormProfile @ onloadwff.js:71 setFieldValue @ onloadwff.js:71 formKeydownListener @ onloadwff.js:71 onloadwff.js:71 Uncaught TypeError: Cannot read property ‘type’ of undefined at e.setFieldValue (onloadwff.js:71) at HTMLFormElement.formKeydownListener (onloadwff.js:71) setFieldValue @ onloadwff.js:71 formKeydownListener @ onloadwff.js:71 I originally thought that I had an error in my input field, perhaps some HTML code was wrong?
Read more →

Learning React TypeScript Patterns

I’m learning TypeScript at the moment (as well as dabbling in other things like Elixir, React Hooks, GraphQL …). But I find it hard to apply my knowledge. It’s all fine and dandy to know what types and interfaces are, but how do I use them? If you have the same problem, you might want to take a look at the articles written by Martin Hochell. I especially enjoyed 10++ TypeScript Pro tips/patterns with (or without) React and Ultimate React Component Patterns with Typescript 2.
Read more →

Surprisingly Good Free TypeScript Udemy Course

I’m very interested in TypeScript at the moment. I love learning new things and TypeScript looks like a useful super-set of JavaScript. It is well supported (by Microsoft), open-source, and seems quite popular according to the State of JavaScript 2018 survey. It also compiles down to plain JavaScript. As a beginner, you can slowly add valid TypeScript instead of having to immediately switch to a completely new language. You can head over to Flavio Copes’s TypeScript Guide to get a sense on what TS has to offer.
Read more →

Creating Protected Routes in React Router

Yesterday I was wondering how I could protect routes in React.js. I have a back-end application written in Node.js which uses middleware (Passport-Next and a requireLogin helper) to protect the server routes. But what about client-side routing? The app uses React Router v4 for routing and React-Redux for state management. The Redux store contains an auth key that tells me if the user is signed in. So, how can I use the Redux state to determine if a user can visit a (client-side) route?
Read more →

Redux: Why?

Redux is a common tool that’s used with React. It creates a central “store”. This store holds your data (the React state). You can connect your React components to the store to read data or use dispatch actions to update the data in your store. The official docs make it sound so complicated: Why Use React Redux? Redux itself is a standalone library that can be used with any UI layer or framework, including React, Angular, Vue, Ember, and vanilla JS.
Read more →

EsLint and Prettier for JavaScript/React in Vim

These are the plugins and settings that I use for JavaScript/React.js-development with (Neo)Vim. Vim Plugins I use minpac as my package manager. VimCasts has a good introduction video on minpac if you’re interested. Useful plugins: pangloss/vim-javascript MaxMEllon/vim-jsx-pretty w0rp/ale Optional: sheerun/vim-polyglot ternjs/tern_for_vim If you use tern.js you need to install the npm package, too. Installing NPM Packages and Setup I use ESLint and Prettier. If you use Create React App skip the ESLint installation because it doesn’t play nice.
Read more →

React: useEffect Hook - Yes/No?

I’m learning how to handle React Hooks. The article Getting Hooked on React Hooks helped me clear up some misunderstandings. But I’m still not sure how to use the Effect Hook when it’s supposed to fetch data on a form submit. In one of my toy apps I have a separate form component. It’s a child to the main app and receives the onSubmit function from the parent. The parent - the main app - defines the onSubmit function which calls the API and captures its result as state.
Read more →

Refactoring to React Hooks

The new version of React, React 16.8 was released this month - and it finally has Hooks. From the official announcement: Hooks let you use state and other React features without writing a class. You can also build your own Hooks to share reusable stateful logic between components. Today I began refactoring my React URL Shortener to using Hooks instead of class components. The app has a simple form input where you can type in a URL.
Read more →

Secret Keys in React

Create-React-App allows you to set environment variables. This is often used to store secret keys, for example, API Keys. You need those to authenticate a request to a third party service (i.e. a call to the Open Weather Map API). Instead of using the key directly in your file, you store it in an .env file and reference it. You don’t commit this .env file to source control (Github, Gitlab, etc.
Read more →

React setState() with prevState and Object Spread Operator

There are some gotchas with React’s setState(). For example, state updates may be asynchronous: React sometimes batches multiple setState() calls for performance reasons. Make sure to set state correctly and to use the latest state. Here are some examples from the official documentation: // Wrong this.setState({ counter: this.state.counter + this.props.increment }); Instead you should use a function which takes the previous state as a first argument. // Correct this.setState((state, props) => ({ counter: state.
Read more →

Handling Events With Callbacks: Prevent Default Behavior in React

The React documentation explains how to handle HTML forms and events. Let’s have a look. Imagine you have an HTML form with an <input> field: the browser will open a new page when the user submits the form. In React, we often don’t want that because we handle our state as part of the main component and we mutate it with setState(). This is a “controlled component”. Here’s an example:
Read more →

Basic Particle.js Setup for React

You can create stunning backgrounds with Particles.js. Luckily, a kind soul has implemented this library as a React component: react-particles-js. react-particles-js is easy to use but it can be tricky to get the CSS working properly. First, add the library to your installation: npm install react-particles-js || yarn add react-particles-js Then add this code to your app: import Particles from "react-particles-js"; const particlesOptions = { particles: { number: { value: 80, density: { enable: true, value_area: 800 } } } }; class App extends Component { render() { return <Particles className="particles" params={particlesOptions} />; } } Now you need to style the Particles component in your CSS file.
Read more →