teleren/devto huggingface dataset:
React Hooks Mini Crash Course
Tags: webdev, javascript, react, todayilearned
Published: 2019-08-30 13:18:53

*This was originally posted as a Twitter thread: [https://twitter.com/chrisachard/status/1167132279333957632](https://twitter.com/chrisachard/status/1167132279333957632)*

Want to learn hooks, but you've been too busy? ⏲

🔥 Here's a mini crash course just for you! 🔥

(code links at the end)


# 1.

Add state to function components by calling `useState` and pass in the initial value.

![useState in function components](https://thepracticaldev.s3.amazonaws.com/i/w6vwtg7h4tua9zjx687q.png)


# 2. 

`useState` returns 2 values in an array:

1. the current value of the state
2. a function to update the state

![useState](https://thepracticaldev.s3.amazonaws.com/i/g05abs40n300ngfpqh5c.png)


# 3.

Call hooks at the top level of a function, and NOT in if statements or loops.

This is required for React to internally keep track of the hook values.

![call hooks at the top level](https://thepracticaldev.s3.amazonaws.com/i/zylvcq2x83hgqggjis6q.png)


# 4. 

Perform asynchronous actions and actions with side effects in the `useEffect` hook

That way, async actions still work across multiple renders

![useEffect](https://thepracticaldev.s3.amazonaws.com/i/huupjc0r02bas71zhwox.png)


# 5.

`useEffect` takes an array of dependencies as the second argument

THIS IS IMPORTANT!  Skipping the dependency list can result in infinite loops, or code that doesn't run when you think it should

![useEffect dependencies](https://thepracticaldev.s3.amazonaws.com/i/froilphkb07oinpb4btz.png)


# 6.

Write custom hooks as function that start with the word `use`

Then use any built in hooks you want

and return (or not) and values and functions

![Custom Hooks](https://thepracticaldev.s3.amazonaws.com/i/9gfvypsrfyw001pfjxg0.png)


# 7.

There are many other built in hooks, but they all follow similar patterns

Get the complete list here: [https://reactjs.org/docs/hooks-reference.html](https://reactjs.org/docs/hooks-reference.html)


# 8.

That's it!  You can now add state and long-running effects to function components.

Class components aren't dead, but hooks do help clean up some component logic.


# 9.

Here are links to code you can try out!

**useState**

{% codesandbox react-hooks-crashcourse-usestate-qcjo8 %}

**useEffect**

{% codesandbox react-hooks-crashcourse-useeffect-e7iwe %}

**Custom Hooks**

{% codesandbox react-hooks-crashcourse-custom-hook-ihfzg %}




&nbsp; 

**Like this post?**
You can find more by:

- Following me on twitter: [@chrisachard](https://twitter.com/chrisachard)
- Joining the newsletter: [chrisachard.com](https://chrisachard.com/)

Thanks for reading!
Laravel course project
Tags: laravel, chartjs, laravelgrid, googlecalendar
Published: 2019-08-30 13:16:34

So, i'm a student of information systems and for the course we need to build a web based application using Laravel framework (v 5.8) for our course project.

<u>**Things I've used for this project**</u>

<b>Scss</b> - Black Dashboard Theme: 
<i>https://www.creative-tim.com/product/black-dashboard-laravel</i>
credits to creative-tim, looks good and I've learned quite a bit from the coding there.

**ChartJS** - <i>https://www.chartjs.org/docs/latest/ </i> learned quite a bit from the documentation on graphs, rendering them and their characteristics, as well as **<u>@arielsalvadordev's</u>** post here on dev.to (my first post read here), who was more than helpful on the subject.

any help on how to use more advanced functions to render the charts via php/controller would be welcome.

<u>**Things i need help implementing in my project**</u>

**Laravel-Grid** - a specific demand to implement Leantony's laravel-grid presented on github : <i>https://github.com/leantony/laravel-grid</i>

I've tried the "How to" but for some reason nothing happens.

**google Calendar** - for this one I will need to elaborate on the app we're building: 

**<u>about the app itself</u>**

the app is for organization's that manage meetings and handle employee tasks related to specific meetings as well as an overall overview of tasks to optimize the organization's efficiency. the calendar comes into play when we want to manage an employees meetings - and possibly grab all the meeting events and details and pass them as an ***.ics*** file to that persons google calendar offsite from our app.

**<u>time picker</u>** - just a good looking time picker and none of that basic html nonsense but rather one of them clocks where you click on the hour and then on the minutes.

**<u>a mailing service</u>** - possibly mailgun or something else

all of this needs to be laravel/php compatible.
I must say I've rendered the grid using a controller and some functions rather than using JS since the data passed to the charts needs to be coming from the DB itself (phpmyadmin/MySQL).

the app itself has a robust set of models, model-relations, controllers and so on.

any help would be welcome.

thank you for helping me make my first steps into the web-dev community.
Rapidly find, prototype, and share new fonts with FontKey
Tags: design, webdev, css
Published: 2019-08-30 13:03:20

Hey all! I just launched [FontKey on Product Hunt](https://www.producthunt.com/posts/fontkey). It was my winning submission to a [Repl.it](https://repl.it/) contest a few weeks ago, and can help you spice up your websites and designs with better fonts. 

Sites like [Google Fonts](https://fonts.google.com/) make it harder than it needs to be to find quality fonts that aren't the most popular. Fonts like Roboto are all over the web, and I'm not saying they're an eyesore. But sometimes you want your site to be different or stick out. 

- Simply press the space bar to cycle through new font styles
- Lock a font in place if you like it to see how it goes with other choices
- Change things like font weight and size easily
- Preview and prototype your selection in realistic website pages
- Get HTML and CSS to put on your website in a single click
- Share a link with friends, coworkers, and anyone else

Anyways, I just wanted to share my work with the Dev.to community and **I would love if you could [go check it out](https://www.producthunt.com/posts/fontkey)**!
How do you make arguments in bash with python?
Tags: python, bash
Published: 2019-08-30 12:43:09

I've recently used django to make websites, and while making them, I found that I could enter arguments into python files. I used `python manage.py <arg>` and it would do the specific things that it's supposed to do. I tried looking into `manage.py` to see how this was possible, but there was nothing there that would allow me to customize these args. (these arguments are honestly hard for me to remember)

So, my question for everyone, is how to make my own arguments? Or how to customize them?
Downloading Files With Groovy and Authentication
Tags: groovy, snippet
Published: 2019-08-30 12:38:49

---
title: Downloading Files With Groovy and Authentication
published: true
description: Code snippet showing how to download files with Groovy and Authentication 
tags: Groovy, Snippet
---

Downloading a file from a URL requiring user authentication with Groovy is as easy as:

```groovy
java.net.Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});
    
destinationFile.withOutputStream { it << new URL(downloadUrl).newInputStream() }
```

**Links**
 
* Stackoverflow: [groovy - Download file with authentication](https://stackoverflow.com/questions/50062880/groovy-download-file-with-authentication)
* Stackoverflow: [Connecting to remote URL which requires authentication using Java](https://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java/496707#496707)
What makes a good article good?
Tags: discuss
Published: 2019-08-30 11:55:41

---
title: What makes a good article good?
published: true
tags: #discuss
---

Hey devs,

Can you share your point of view? What are the qualities of a good article?

Is it...
* Easy to read.
* Has some great information.
* Funny / Enjoyable.
* Has someone's experience or story.
* What else?
Is Prototyping necessary?(UX/UI)
Tags: ux, webdev, productivity, discuss
Published: 2019-08-30 11:54:42

#Introduction#

Beginning development on a project without a prototype is like trying to drink water using only your tongue, you can do it but it will take longer.

Think of prototyping as the conversation you have with your ideas. It solidifies exactly what is expected of you & will save a lot of time in the long run. Even if it may seem like taking a scenic route to your destination at first.

For some it may be obvious to build the plans before beginning construction, but for others (like myself) who let their excitement get the better of them & just want to start coding, the word prototype sounds like some fogey word for overcomplicating things.

Let's see some pros & cons of prototyping & why **you** (or your designer) should build them before delving into the matrix.

![matrix-gif](https://media.giphy.com/media/l41lRvFQYdlfvDTLG/giphy.gif)

#Pros#

Prototypes make for a really good first deliverable on a project. It outlines requirements for the developer, let's the client/user have an early look at the product, and is a fast way to exchange helpful & relevant feedback. 

It gives the user or the client a feeling of involvement early on in the development life cycle, they will have a working model to click through and test the look and feel which is often their main focus.

If any changes need to be made, they can be clarified and resolved before any amount of time has been spent on developing the feature. This reduces development costs, time, and any confusion or uncertainty that the developer may have approaching a specific problem. 

#Cons#

The biggest problem when it comes to prototyping is explaining to the user that the prototype **IS NOT** the final product. 

In some cases the developer/designer could spend excessive time trying to perfect a prototype, when the intention of a prototype is to be built efficiently.

I'm clutching at straws trying to think of more cons. I guess thats why its called a **PRO**totype.

![clutching-straws](https://media.giphy.com/media/Ve9pOjJRxkW2c/giphy.gif)

#Closing#

If you're still reading this after that joke,

Here's a list of some cool tools i've checked out:

[Adobe XD](https://www.adobe.com/products/xd.html)
[Marvel App](https://marvelapp.com/)
[Axure RP](https://www.axure.com/)
[InVision](https://www.invisionapp.com/)


My knowledge is limited to my experience, I'd like to hear your thoughts
What are the differences between production code and test code?
Tags: testing, tdd, discuss, help
Published: 2019-08-30 11:40:34

Let's say this is like a sort of survey. How do you see the differences between production code and test code?

Feel free to add anything that comes to your mind.

Let me start with two things.

* Production code often tends to be DRY, test code tends to be more WET (Write Everything Twice)
* Production code tends to be generic, while test code tends 

Unleash your mind!
What do you do when you have no internet or limited access to the internet? 
Tags: discuss, productivity, help
Published: 2019-08-30 11:24:11

Right now I'm on vacation and I have a very limited access to the internet. Also I'm on the country side with no real activities like going to the cinema or gym or going for a coffee.

So my wisdom is are you in such situations and if yes what do you do in that time?

**👋Say Hallo!** [Instagram](https://www.instagram.com/lampewebdev/) | [Twitter](https://twitter.com/lampewebdev) | [LinkedIn](https://www.linkedin.com/in/michael-lazarski-25725a87) | [Medium](https://medium.com/@lampewebdevelopment) | [Twitch](https://dev.to/twitch_live_streams/lampewebdev) | [YouTube](https://www.youtube.com/channel/UCYCe4Cnracnq91J0CgoyKAQ)
ngx-smart-modal 'onDataAdded' called many times
Tags: help, angular, typescript
Published: 2019-08-30 10:50:15

I'm new using angular8 and the library ngx-smart-modal to make a list of clients each one with one button to remove him from the list. When I click on the button I show a confirm modal and when click on accept, passes the client code to another compoment wich search that code and remove the affected index from the array list.

Problem is: in the first modal opened, 'onDataAdded' is called once (expected behavior). In the second is called twice (not expected) and so on...

When I click on 'delete', it triggers this function from 'clients' component which opens the confirmation modal and waits for response (onDataAdded):

```
delClientModal( index: number ) {
  this.clientToRemove = this.clients[index];
  this.clientService._passClient(this.clients[index]);
  this.ngxSmartModalService.getModal('delClientModal').open();
  this.ngxSmartModalService.get('delClientModal').onDataAdded.subscribe((data: any) => {
    const indexToRemove = this.clients.findIndex(i => i.clientcode === data);
    if (indexToRemove >=  0) {
      this.clients.splice(this.clients.findIndex(i => i.clientcode === data), 1);
    }
  });
}
```

When I click on accept, it triggers this function from 'client' component wich send the client code to clientService (for api operations) and set the data to de modal for 'onDataAdded' to catch it:

```
delClient(clientcode: string) {
    this.clientService._deleteClient(this.client);
    this.ngxSmartModalService.setModalData(clientcode, 'delClientModal');
    this.ngxSmartModalService.resetModalData('delClientModal');
  }
```

What I'm not getting right?
Python Bluetooth and Wifi?
Tags: python, bluetooth, wifi
Published: 2019-08-30 10:31:39

---
title: Python Bluetooth and Wifi?
published: true
description: A pet project to include simple wifi and bluetooth APIs
tags: python, bluetooth, wifi, OSS
---

I started working on a desktop application for a lecturer of mine a  little while back. The application was to get both bluetooth and wifi devices graphed with their rssi values. I decided to try my hand at using python (majorly because I had seen pybluez)

This quickly spiralled into wanting to create a python package that has these inbuilt functionalities and voila <a href="https://github.com/bisoncorps/signalum">Signalum</a> was born. My logic was that if I could create a library then the PyQT application would simply plug into it.

I only have very limited experience in using python so I'm certain that I'm doing countless things wrong so I would appreciate pull requests, suggestions, etc.

Please be nice ☺
Introduction to Ansible Part 2
Tags: ansible, ubuntu, digitalocean
Published: 2019-08-30 10:17:52

Part 2 of my quick Introduction to Ansible blog series! In this article I'm going though the Ansible installation and some of the important configuration files.

As always for the hands on part I'll be using a few @digitalocean droplets for the hands on demo!

Part 2:

https://bobbyiliev.com/blog/introduction-to-ansible-part-2

Let me know if you have any questions!
dev.to is shadow-banned on Reddit
Tags: reddit, discuss, watercooler, meta
Published: 2019-08-30 10:07:09

---
title: dev.to is shadow-banned on Reddit
published: true
tags: reddit, discuss, watercooler, meta
---

Yesterday I have written [my first article on dev.to](https://dev.to/gajus/dynamically-generating-sql-queries-using-node-js-2c1g) and shared it on Reddit. [I have a good amount of Reddit karma](https://www.reddit.com/user/gajus0) and I was expecting it to become a trending article. However, it got no upvotes. I figured maybe it didn't resonate and deleted those posts after 6 hours.

I have tried posting on Reddit today again and again got 0 upvotes. Perhaps my account got banned, I thought. I have created a new account and [posted a modified link](https://www.reddit.com/r/node/comments/cxenwf/dynamically_generating_sql_queries_using_nodejs/) – again, 0 upvotes. This is where I realised that the post does not even appear on Reddit. It does not appear if you search for it and it does not appear if you sort by "new".

To validate this, I have posted the same link on a sub-reddit where I am a mod. Sure enough, the post was automatically removed and put into a moderator queue.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/kvu56bp5mwxav1gmu6c8.png)

In fact, there have been [no posts linking to dev.to](https://www.reddit.com/search/?q=url%3A%22dev.to%22&t=day) that were approved in the last 24 hours.
Automated resource scheduling for project management
Tags: management
Published: 2019-08-30 09:58:05

I've been looking around at the PM resource scheduling solutions that exist, but they all want me to manually pick people and assign them tasks, and quite often resolve conflicts manually. Are there any tools that will take my project with its tasks and automatically generate a schedule across all resources taking into account conflicts, leave time, due dates, task skill requirement, etc.? I want to spend my time focusing on the progress of the project, clearing roadblocks for people, not shuffling around calendars.
MEASURING COMPONENT PERFORMANCE USING REACT PROFILER API
Tags: reactprofilerapi, react, api, devtoolswebdev
Published: 2019-08-30 09:50:55


Good performance in React application is easy to achieve and also easy to miss, but missed performance loopholes can be more expensive than we can imagine. React provides some exceptional tools to measure performance, and anything measurable can be better monitored and controlled.

The React profiler is available as part of React devtools in Google chrome extensions, which provides an excellent way to measure and record the performance of the application. At every component level, it ensures the awareness of the performance aspect in the ongoing application development. The new profiler provides a consolidated view of the application components rendered with relative ranking details, grouped by commits in the form of different charts – Flame chart, Ranked chart and specific component charts.

The latest React 16.9 is out, in which the new features and notable bug fixes make developers job easy.

With this new version of React, comes the React Profiler API which is now available to measure component performance directly. It is the API which is also internally used by the devtools profiler. It provides a new way to measure the performance at each of the individual component levels by tracking it programmatically.

With the new release, it is easier to measure and control performance at each component level:

The frequency of render
The time for each render
The base time for the initial mount or worst-case render time

The profiler API is particularly helpful in larger applications to get the performance view and impact of regression on a specific component.

HOW TO USE THE REACT PROFILER API?

The new Profiler API can be included as an additional tag around each of the components to measure its performance, by giving it a unique id and including a common handler for render.

const MyGrid = (props) => {
return (
<React.Profiler id="MyGrid" onRender={onRenderCallback}>
<IGrid {...props} />
</React.Profiler>
);
};

Use Profiler tag around any number of components to measure their performance, assign a unique id value to facilitate the identification and thus help to track each component uniquely in the Profiler tree.
Define a generic handler, which is called each time the component is rendered, for the first mount and each subsequent update. This can be defined as a common utility function with the profiling data handling logic and can be used across the application whenever profiling any component.

The handler receives the profiling details which can be used appropriately to measure and track the performance parameters of the component.

function onRenderCallback(
id, 
phase, 
actualDuration, 
baseDuration, 
startTime, 
commitTime, 
interactions 
) {
//Logic to handle the profiling details
console.log( 'The component', id, ', The phase', phase,', Time taken for the update',  actualDuration, baseDuration, startTime, commitTime, interactions);
}



Source:https://walkingtree.tech/measuring-component-performance-using-react-profiler-api/
ES-Next dynamic import
Tags: javascript, esnext, import, dynamic
Published: 2019-08-30 09:44:40

#### Problem

Recently when writing a project of mine, I've written some javascript like this:

```javascript
import itemA from '../items/itemA';
import itemB from '../items/itemB';
import itemC from '../items/itemC';
import itemD from '../items/itemD';
```



I'd really like some syntax like this:

```javascript
for(const id of ['A','B','C','D']) {
    import (item+id) from '../items/item' + id;
}
```



Turned out there's this `stage 4 proposal of ECMAScript` called `dynamic import`  that goes like:

```javascript
(async () => {
  await import('./my-app.mjs');
})();
```

and it's supported by all modern browsers as well as node.



#### Failed Attempt

Then I went on writing some line code like this:

```javascript
importedItems = await Promise.all(
  itemNames.map(async itemName => {
    try {
      const imported = await import(`../items/${itemName}`);
      logger.debug(`Imported item: ${itemName}`);
      return imported;
    } catch (err) {
      logger.warning(`Failed to import item: ${itemName}`);
      return null;
    }
  })
);
```

But for later use of `importedItems`, a `TypeError` has been raised stating that the `importedItems` are actually type of `Module` instead of expected `item`. I tried manual type casting like this:

```javascript
return Item(imported);
```

But it didn't work and since it's not yet standardized feature (Due to be standardized in ECMAScript 2020), there's little information about it so I have to figure it out myself.

After a long time with `JSON.stringify()` and `console.log` I finally figured it out.

#### Solution

It should work like this:

```javascript
return imported.default;
```

Full working snippet

```javascript
importedItems = await Promise.all(
  itemNames.map(async itemName => {
    try {
      const imported = await import(`../items/${itemName}`);
      logger.debug(`Imported item: ${itemName}`);
      return imported.default;
    } catch (err) {
      logger.warning(`Failed to import item: ${itemName}`);
      return null;
    }
  })
);
```



#### Reason

The reason is that when we use an `import` statement like this:

```javascript
import item from './itemA';
```

 it automatically loads the `default export` of module `'itemA'` into the `item`.

But when we do expression like dynamic import like this:

```javascript
(async () => {
  const item = await import('./itemA');
})();
```

the item is a `Module` , by accessing `Module.default` we are able to fetch its default export, same goes for any other exports.

originally posted on: https://blog.llldar.io/Article/View/44
Parse me a numeric html entity
Tags: challenge, programming, javascript
Published: 2019-08-30 09:32:33

---
title: Parse me a numeric html entity
published: true
description: The challenge: to take in a string and turn numerically represented html entities into their expected characters.
tags: challenge, programming, javascript
---

I saw the following question:

{% stackoverflow 57712841 %}

It's been closed as a dupe, but that didn't discourage me from wanting to figure it out for myself.

So, the challenge is: for any given string input, replace any numerically represented html entities with the correct character.

Remember, the largest codepoint is 0x10ffff.

Some test cases:

```javascript
'&#xf6;_&#246;' // expected 'ö_ö'
'Hello &&&#x;'  // expected 'Hello &&&#x;'
'&#x123 &#x123;'  // expected '&#x123 ģ'
'&#x110000;'    // expected '&#x110000;'
```

I'll post my attempt below!