teleren/devto huggingface dataset:
5 React Snippets to Get You Started
Tags: react, code, javascript, flatiron
Published: 2019-06-30 01:43:47

As an avid code reader, I've always stashed away beautiful pieces of code that caught my eye. This has been effective habit for developing my code vocabulary.

More recently, I started using [Code Notes](https://lauthieb.github.io/code-notes/), a free, open source app for keep track of code snippets.

Since Code Notes saves my snippets on my computer, I wasn't sure of the best way to share these.  So, for now, I'm posting the snippets to this article, though I may move them elsewhere when time permits.


####Initializing state without props
```javascript
class App extends React.Component {
  state = {
    empty_array_state: [],
    empty_string_state: ""
  }
```

####Doing a (GET) fetch request 
- This should happen in componentDidMount()
```javascript
  componentDidMount() {
    fetch(your_url)
    .then(res => res.json())
    .then(data => {
      this.setState({your_state:data})
    })
  }
```

####Handling events
- Here you can setState based on a user's input or when any event is fired
```javascript
  handleEvent = (event) => {
   ....add code here....
  }
```

####Iterating
- You can still use loops within render()
```javascript
  render(){

    let listItems = this.props.myList.map(item => {
      return(
        <Item
          id={item.id}
          name={item.name} />
    )
  })
    return (
      <div>
        {listItems}
      </div>
    );
  }
```

####Using absolute imports
- This prevents your code from breaking in the event that you move your files
```javascript
import { Header } from 'components/Header'
import { HeaderContainer } from 'containers/HeaderContainer'
import headerStore from 'store/headerStore'
```

I came across absolute imports while reading Alligator.io, one of my favorite React resources. If you'd like to learn more about absolute imports, check it out [this post](https://alligator.io/react/clean-import-statements-in-react/)
What is your favourite Git command? 
Tags: discuss, git
Published: 2019-06-30 01:06:24

I'm curious to know, what is your favourite Git command?

Mine is "git commit --amend", which let's you change your last commit message. I manage to mess up a commit message at least once a day 😅

For the sake of clarity, please include what the git command does so  we can all learn from one another! 😄
Making Splash Screens for a Capacitor/Android Application
Tags: ionic, capacitor, ios
Published: 2019-06-30 00:00:00

---
layout: post
title: Making Splash Screens for a Capacitor/Android Application
date: '2019-06-30'
author: Michael Callaghan
tags: ionic,capacitor,ios
layout: post
feature: assets/img/bravo-icons.png
thumbnail: https://walkingriver.com/assets/img/bravo-icons.png
cover_image: https://walkingriver.com/assets/img/bravo-icons.png
canonical_url: https://walkingriver.com/make-splash/
published: true
---

This is a follow-up to my post from yesterday, about making icons and splash screens for Ionic/Capacitor apps. Turns out, making a splash screen for iOS was simple. Just drop three 2732x2732 files into the project, and Xcode takes care of the rest. Likewise, Android Studio will take a large png file and make you a set of perfect icons. But making Android splash screens was harder, so I recreated my pattern from yesterday and made a script to do the hard stuff for me.

<!--more-->

> You can read about my [Ionic 3 - 4 and Capacitor experience here](https://walkingriver.com/ionic-3-to-4/).

To create the Android splash screen, I started with the same 2732x2732 PNG file I used for the iOS project. Using the same `sips` command I had used yesterday, and the file sizes Android Studio and Capacitor gave me, I came up with this version of the shell script. 

```
#!/bin/bash

###### 
# Make a bunch of Android splash screens Master image.
# Given an image at least 1920x1920 pixels named splash.png, resize and create a
# duplicate at each specified size. Add new sizes as needed. When finished,
# copy the resulting images into your Android project, under the res folder.

mkdir -p ./res
function resize {
  w=$2
  h=$3

  echo $1 into $4

  [ -d "./res/$4" ] || mkdir ./res/$4

  if [[ $w -ge $h ]]; then
    sips -Z $w -c $h $w --out ./res/$4/splash.png $1
  else
    sips -Z $h -c $h $w --out ./res/$4/splash.png $1
  fi
}

resize $1 480 320 drawable
resize $1 800 480 drawable-land-hdpi
resize $1 480 320 drawable-land-mdpi
resize $1 1280 720 drawable-land-xhdpi
resize $1 1600 960 drawable-land-xxhdpi
resize $1 1920 1280 drawable-land-xxxhdpi
resize $1 480 800 drawable-port-hdpi
resize $1 320 480 drawable-port-mdpi
resize $1 720 1280 drawable-port-xhdpi
resize $1 960 1600 drawable-port-xxhdpi
resize $1 1280 1920 drawable-port-xxxhdpi
```

Like yesterday's script to create iOS icons, this one is pretty straightforward. It is a lot of brute force, and assumes a happy path. Unlike yesterday's, this one actually allows you to specify the splash screen to be converted, and it will then build the appropriate `res` folder. Simply take those files and drop them into your Android Capacitor project. You'll find them in `./android/src/app/main/res`.

Feel free to make suggestions on improvement.



# Feedback Appreciated
Do you have any comments or questions? Did I make any mistakes in this post? Let me know on Twitter. I'm [@walkingriver](https://twitter.com/walkingriver).
Mastering :focus-within
Tags: html, css, a11y, webdev
Published: 2019-06-29 09:38:59

Dropdown-on-hover pattern is used in interfaces for a very long time. And most of that time, these dropdowns are not fully acccesible. For example, if you navigate via keyboard there is no chance that you will get into this dropdown and select something hidden in it.

But everything has changed when `:focus-within` landed in browsers. And according to __caniuse.com__ this code is enough for about 81% of users to make them a little happier:

```html
<div class="dropdown" tabindex="0">
  <p class="dropdown__title">This is dropdown</p>
  <div class="dropdown__wrapper">
    <a href="#">Some hidden link</a>
  </div>
</div>
```
```css
.dropdown {
  position: relative;
}
.dropdown__wrapper {
  width: 0;
  height: 0;
  overflow: hidden;
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1;
}
.dropdown:hover .dropdown__wrapper,
.dropdown:focus-within .dropdown__wrapper {
  width: 100%;
  height: auto;
  overflow: visible;
}
```
Note that you have to add `tabindex="0"` to the dropdown container, so it become focusable.

So, we’re done. But what about that near 19% of browsers that doesn’t support `:focus-within`? Javascript all the things!

```javascript
// so here is module pattern begins
;(function () {
  // get all of dropdowns on page and define active class
  const dropdowns = Array.from(document.querySelectorAll('.dropdown'))
  const dropdownActiveClass = 'dropdown--active'

  // add event listeners to focusin and focusout to our dropdowns
  dropdowns.forEach(dropdown => {
    dropdown.addEventListener('focusin', focusinListener)
    dropdown.addEventListener('focusout', focusoutListener)
  })

  // if focus is inside dropdown, add active class
  function focusinListener (event) {
    event.target.closest('.dropdown').classList.add(dropdownActiveClass)
  }

  // if focused element is not dropdown, remove active class from all dropdowns
  function focusoutListener (event) {
    if (!document.activeElement.classList.contains('dropdown')) {
      dropdowns.forEach(dropdown => {
        dropdown.classList.remove(dropdownActiveClass)
      })
    }
  }
}())

```
And we have to update CSS:
```css
.dropdown:hover .dropdown__wrapper,
.dropdown:focus-within .dropdown__wrapper,
.dropdown--active .dropdown__wrapper {
  width: 100%;
  height: auto;
  overflow: visible;
}
```
And then just enjoy this accessible dropdown! Full demo to play (use your Tab button):

{% codepen https://codepen.io/twhite96/pen/BgJEVy %}
TIL: Error catch-bindings are finally optional
Tags: javascript
Published: 2019-06-30 13:05:13

---
title: TIL: Error catch-bindings are finally optional
published: true
tags: javascript
canonical_url: https://www.stefanjudis.com/today-i-learned/error-catch-bindings-are-finally-optional/
---

I just made my way through my weekly newsletters and came across [the optional catch-binding proposal](https://github.com/tc39/proposal-optional-catch-binding) which shipped in [ES2019](https://2ality.com/2018/02/ecmascript-2019.html).

The language addition allows developers to finally omit the error argument when dealing with `try/catch` statements. This feature can become especially handy in modern JavaScript code that uses `async`/`await` a lot.

A few lines of code describe it best:

```javascript
// classical try/catch
// ✅ works
try {
  throw new Error('oh noes');
} catch(e) {
  console.log(`Error!!! But, I don't care about the error object...`);
} 



// try/catch without error arguments
// ❌ throws "Uncaught SyntaxError: Unexpected token ')'"
try {
  throw new Error('oh noes');
  
//     👇 omitting the error argument doesn't work...
} catch() {
  console.log(`Error!!! But, I don't care about the error object...`);
} 



// try/catch without error binding
// ✅ works again 🎉
// (across majors Edge, Firefox, Safari, Chrome)
try {
  throw new Error('oh noes');

//     👇 omitting `()` altogether works now 🎉
} catch {
  console.log(`Error!!! But, I don't care about the error object...`);
}
```

This language addition was a little bit controversial, and people [discussed it hotly in the proposal repository](https://github.com/tc39/proposal-optional-catch-binding/issues/2). Personally, I think it can be handy in some instances of quick prototyping where perfect error handling is secondary.

Reading about the feature, it turned out that major browsers (Chrome, Safari, Edge, Firefox) support the addition already. 🎉 If you have to support more than the latest and greatest browsers, you can also use [the babel plugin to use this new language feature today](https://babeljs.io/docs/en/babel-plugin-proposal-optional-catch-binding). 

*(The MDN docs are currently outdated, and [a PR is pending](https://github.com/mdn/browser-compat-data/pull/4403))*

If you want to learn more about it, here are some additional resources:

- [Dr. Axel Rauschmayer's take on the feature](https://2ality.com/2017/08/optional-catch-binding.html)
- [the "optional chaining proposal" on GitHub](https://github.com/tc39/proposal-optional-catch-binding)
AWS Lambda: how to share code between functions in a monorepo
Tags: aws, lambda, programming, serverless
Published: 2019-06-30 08:34:12

---
title: AWS Lambda: how to share code between functions in a monorepo
published: true
tags: AWS,Lambda,Programming,Serverless
canonical_url: https://theburningmonk.com/2019/06/aws-lambda-how-to-share-code-between-functions-in-a-monorepo/
---

A while back, a client asked me “how can I share business logic between services in a Node.js monorepo?”. The TL;DR of it is:

- Encapsulate the shared business logic into modules, and put them in a separate folder.

![](https://theburningmonk.com/wp-content/uploads/2019/06/img_5d17f2d8daa8f.png)

- In the Lambda handler functions, reference the shared modules using relative paths.

![](https://theburningmonk.com/wp-content/uploads/2019/06/img_5d17f2efb3883.png)

- Use webpack to resolve and bundle them into the deployment package. If you use the Serverless framework, then check out the [serverless-webpack](https://github.com/serverless-heaven/serverless-webpack) plugin. For example:

![](https://theburningmonk.com/wp-content/uploads/2019/06/img_5d17f3078ba47.png)

- **Deploy every service on every commit**. You can do this with a simple script like the following.

![](https://theburningmonk.com/wp-content/uploads/2019/06/img_5d17f31a6b05f.png)

To see how everything fits together, check out [this demo repo](https://github.com/theburningmonk/lambda-monorepo-code-sharing-demo). It has CI/CD set up already through [drone.io](http://drone.io) and you can see a recent deployment of all the services in the monorepo [here](https://cloud.drone.io/theburningmonk/lambda-monorepo-code-sharing-demo/3).

But wait! How do I choose between having a monorepo vs a repo per service?

Don’t worry, I’ve got you covered for that too ;-) You can read about my thoughts on the two approaches [here](https://lumigo.io/blog/mono-repo-vs-one-per-service/).

Check out [theburningmonk.com](https://theburningmonk.com) for more of my articles.
How do you handle the disposable IF statements ?
Tags: discuss, webdev
Published: 2019-06-29 22:39:04

Hi there,

Sometimes you need to write a conditional block that will only be executed once or for a brief period of time then the condition won't be satisfied again, like for ever.

An example for these IFs is

```js

// User level IFs
if (!user.activated) {
 alert('please activate your account');
 return false;
}

```
```php
// Application level IFs
if ( ! isAppProperlyInstalled() ) {
  die('Please, check the installation guide...');
}
```

The idea of that residing code that won't be executed again has been bothering me for years. I'm kind of picky and sometimes go crazy about micro-optimization, but sometimes I just ignore it. However, I feel that there's a great design pattern that I'm not aware of that may make me feel better about it. 

What do you think ? Do you share the same feeling ? and how are you dealing with it ?

---
Photo by Carolina Pimenta, [Unsplash](https://unsplash.com/photos/ledpW0Zk2fU)
What do you listen When You Code?
Tags: discuss, music, coding
Published: 2019-06-29 22:38:16

### My list
{% youtube Gque9WflakY %}
{% youtube 8XJ6r4U171I %}
{% youtube IPSRJ0CBqBw %}
{% youtube 6LCqUkadCjg %}
{% youtube DSGyEsJ17cI %}
{% youtube 7JqKRqOmzi0 %}
{% youtube 5VB1RvyfISM %}


### sometimes I use this
{% youtube jX6kn9_U8qk %}


# What do you listen When you code?
When isn't inheritance used?
Tags: discuss
Published: 2019-06-29 22:27:41

---
title: When isn't inheritance used?
published: true
tags: discuss
---

I was asked in an interview "when would you _not_ use inheritance."  And I paused because the only thing I could articulate was "when it doesn't make sense?"

This was for a .NET position, by the way.

The thing that puzzled me about this question was that I didn't really know how to say it.  You don't use inheritance when it doesn't apply to the software architecture.  And that's more or less what I said, but I was wholly unsatisfied with my answer.

After the interview was done as I was doing my after-action report, I had this sneaking suspicion that he wanted me to mention composition.  And as I write this post, I also feel like I should have added immutability, you don't want inheritance on objects that are meant to be immutable (like Java's `String` class).

But now it bothers me.  What would be a good answer to that question?
Empathy with another dev's code
Tags: dev, begginers, carrers, discuss
Published: 2019-06-29 21:40:43

---
title: Empathy with another dev's code
published: true
description: How can we focus on what's important and not blame who wrote some code that we don't like.
tags: dev,begginers,carrers,discuss
---

<p>I have worked as a software developer for few years now, and the most common thing that I had to deal with, was figure how works some code that another dev wrote.</p>
<p>By the time I started it was not rare to listen me criticizing the code that someone else wrote even if that code was working fine and in most cases based on personal preferences and choices.</p>
<p>Something that I learned as the time passes was to have empathy with another developer's code. Each person has your own backgrounds, convictions, policies and mental model, as long that their code follows the team/company conventions and  not present some real issue there is nothing to worry about.</p> 


<h5>So I decided to make a simple work flow</h5>
<div>
![empathy-flow](https://thepracticaldev.s3.amazonaws.com/i/5voa17nm68n0enjkt5nn.png)
</div>


<p>
I hope to help beginners developers to recognize this thoughts and follow some logical work flow before blame, judge or criticizing some work colleague.
</p>


<h3>What is your work flow ? </h3>
React hooks & the closure hell 2
Tags: react, reacthooks, javascript, frontend
Published: 2019-06-29 21:19:33

---
title: React hooks & the closure hell 2
published: true
description: Since event handlers are closures we need to either re-create them on each render or whenever one of it's dependencies changes. This means components that only depend on the event handler (and possibly not on the handler's dependencies) will have to re-render too.
tags: react, reacthooks, javascript, frontend
---
#React hooks & the closure hell 2

This is a continuation of my last post ([React hooks & the closure hell](https://dev.to/anpos231/react-hooks-the-closure-hell-71m))

## Just a quick tl;dr
Functional components require you to regenerate all your callbacks on each re-render because there is nowhere to store them (In old class based components you could just bind your functions as method and you were good to go).


Previous solutions required you to either specify dependencies so they could be passed to existing function, or to work with objects that would store current properties and values. I think these solutions were cumbersome, so I kept tinkering and created even better solution!

## Meet `useCallbacks`
```jsx
const useCallbacks = (reinit) => {
  const data = useRef({ callbacks: {}, handlers: {} })
  const callbacks = data.current.callbacks
  const handlers = data.current.handlers
  
  // Generate new callbacks
  reinit(callbacks)
  
  // Generate new handlers if necessary
  for (let callback in callbacks) {
    if (!handlers[callback]) {
      handlers[callback] = (...args) => callbacks[callback](...args)
    }
  }
  
  // Return existing handlers
  return handlers
}
```

## Usage ([Try here](https://codesandbox.io/s/react-hooks-usestate-sj9zo))
```jsx
const App = () => {
  const [value, setValue] = useState(1);

  const handlers = useCallbacks(callbacks => {
    callbacks.handleClick = (event) => {
      setValue(value + 1)
    }
  })

  // Check console, the state has changed so the App function will re-run
  // but memoized ExpensiveComponent won't be called because the actual handling
  // function hasn't changed.
  console.log(value)

  return (
    <div className="app">
      <ExpensiveComponent onClick={handlers.handleClick} />
      <button onClick={handlers.handleClick}>
        I will not trigger expensive re-render
      </button>
    </div>
  );
};
```

And that's it!
You don't have to specify any dependencies or work with messy objects.
The callback is regenerated but the actual handling function is not, so your pure components or memoized components won't re-render unnecessarily.

Everything works as hooks intended!
Tell me what you think.
Have you worked on an AI Project that related to chemistry?
Tags: machinelearning, computervision, python, discuss
Published: 2019-06-29 21:11:18

a friend of mine is now in the latest year of his college of Computer Science, and he is going to build an AI project for his graduation to show it to his University Teachers
he told me that he would like to build a Project related to chemistry, have ever anyone of you had envolved in a chemistry project before?
if not, can you suggest an idea of a project that could be amazing to work on and build
React Customised Table View depending on user logged in - user can add remove columns specific to them as needed
Tags: reactnative, react, javascript, datagrid
Published: 2019-06-29 20:36:29

Hi there,

I wonder if someone could help me through this problem.

I have a settings table.  Every user has the same starting base settings table with the same number of columns although content is different. It has column A and column B as dimensions to this table.

I have multiple users.

User 1 may want to add via new columns or dimensions to the table with customised headers - they may want 1 or 2 or 3 new columns/dimensions

User 2 may want to add 10 new dimensions to the table with their own customised headers for the columns.

The cell contents would be different for both user 1 and user 2.

How would I manage this in terms of storage?  Would you store "settings" for user 1 and user 2 separately in the Postres database and then load these when the user selects the table component?

After this I then have a fact table and users will be able to tag their transactions users the dimensions unique to them in the other settings table.

In the end the final settings table will look completely different depending on the user logged in.
The Pragmatic Programmer 20th Anniversary Edition Series
Tags: thepragmaticprogrammer, book, programming, education
Published: 2019-06-29 20:07:00

---
title: "The Pragmatic Programmer 20th Anniversary Edition Series"
published: true
tags: ["The Pragmatic Programmer", "book", "programming", "education"]
categories: ["The Pragmatic Programmer"]
description: "Introducing a a very pragmatic blog post series."
---

> This post originally appeared on [steadbytes.com](https://steadbytes.com/blog/the-pragmatic-programmer-20th/intro/)

<div></div>

> For twenty years, the lessons from The Pragmatic Programmer have helped a generation of programmers examine the very essence of software development, independent of any particular language, framework, or methodology.

> -- [The Pragmatic Bookshelf](https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition)

The original version The Pragmatic Programmer by David Thomas and Andrew Hunt has been an **extremely** influential book for me and (without a shadow of a doubt) many others. However, although a large amount of the _essence_ of the book is still relevant today, most of the technological references are very much outdated. The authors recognise this:

> But 20 years is many lifetimes in terms of software. Take a developer from 1999 and drop them into a team today, and they’d struggle in this strange new world. But the world of the 1990s is equally foreign to today’s developer. The book’s references to things such as CORBA, CASE tools, and indexed loops were at best quaint and more likely confusing.

> -- "Preface to the Second Edition" [The Pragmatic Programmer 20th Anniversary Edition](https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition)

So I was indeed excited to hear that the 20th anniversary edition will contain brand new topics alongside revised/updated topics from the original book! The new edition follows the same format as the original, with **challenges and exercises** throughout each section - perfect for a blog post series. In this blog post series I will be providing my own answers to the challenges and exercises as well as thoughts/analysis on some of the topics.

To end this introduction, I would like to thank David Thomas and Andrew Hunt for their dedicated work on The Pragmatic Programmer and I encourage readers to purchase the book from [The Pragmatic Bookshelf](https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition).

- Note that at the time of writing, the book is in Beta so minor changes and updates may be made before it's full release (all of which are available to Beta purchasers as and when the updates are made public).
Will you be at OSCON 2019?
Tags: discuss, opensource
Published: 2019-06-29 19:57:03

---
title: Will you be at OSCON 2019?
published: true
description: A great conference with great tech and even greater people
tags: discuss, opensource
---

Is this year's [OSCON](https://conferences.oreilly.com/oscon/oscon-or) in Portland, Oregon, on your agenda? 

I'll be there too. Let's make some live DEV connections while there to hype that "hallway track" even more!