teleren/devto huggingface dataset:
Best way to handle lots of logic inside React Class Components
Tags: discuss, react, oop, javascript
Published: 2021-02-22 23:14:12

# Context

We have a (very huge) application where sometimes there are files with 1000+ lines of code. What makes these files big are the logic of some methods. Wether we have too much logic on our component or not is not something I would like to discuss, at the end of the day, this is a production app and we have limited resources and limited time, so we need to find the best way to optimize the codebase while meeting deadlines (welcome to the real world!).

For example, suppose I have something like this:

```js
class MyComponent extends Component {
    constructor() {
        // Lots of bindings
    }
  
    myHugeMethod1() {
        // Lots of logic that depends on this.props and probably other (hopefully smaller) class methods
    }

    myHugeMethod2() {
        // Lots of logic that depends on this.props and probably other (hopefully smaller) class methods
    }
  
    render() {
        // the render
    }
  }
```

## Our approach

We have obviously thought about lots of things: utility functions, static methods and classes with a single method. I personally find the last one the best approach. And this is what we have agreed to be the best approach (although we are not 100% sure):

```js
import MyHelperMethod1 from "./MyHelperMethod1";
import MyHelperMethod2 from "./MyHelperMethod2";

class MyComponent extends Component {
    constructor() {
        // Lots of bindings
        const myHelperMethod1 = new myHelperMethod1(fixedProperties);
        const myHelperMethod2 = new myHelperMethod2(fixedProperties);
    }
  
    myHugeMethod1() {
        myHelperMethod1.setVariableProperties(variableProperties)
        myHelperMethod1.help()
    }

    myHugeMethod2() {
        myHelperMethod2.setVariableProperties(variableProperties)
        myHelperMethod2.help()
    }
  
    render() {
        // the render
    }
  }
```
The `variableProperties` variable is probably an object. And probably `this.props` is going to be included inside of this object. It can feel odd, but that's how I do it.

## How do you do it?

I want to hear about your approaches to handle these situations.
Intro
Tags: showdev, writing, startup
Published: 2021-02-22 22:58:32

Hi there! I'm leits.

This is my public journal where I think aloud and share what I learned while making stuff (mostly software and around).

Behind my back are seven years in software engineering. During this time, I saw many products from the inside. Launched and scaled a big bunch of them. Made many great and some not the best architectural decisions.

The thing I learned well over that time:

There is no right way to make new stuff

Every time you start doing something new, you move by trial and error. It's quite healthy to master new skills and build your own opinion. 

I already have experience in building things in public. 

In early 2020, when I had a lot of meetings, I created [MeetingBar](https://apps.apple.com/app/id1532419400) to be more comfortable with them. I published this project, and now it has 17K+ installations. The public codebase on [GitHub](https://github.com/leits/MeetingBar) gathered 1.8K stars and 20 contributors.

I realized that my experience in building and running projects can be useful. Or just interesting for someone.

Now I'm working on an analytics service for the open-source community. In this place, I'll share my trials and errors on how I make stuff.

Sign up now, so you don't miss the first issue:
[https://leits.substack.com](https://leits.substack.com/p/coming-soon?r=h8qz8&utm_campaign=post&utm_medium=web&utm_source=devto)
React Functional Components using TSX
Published: 2021-02-22 22:57:12

Today I wanted to see how to create a React Functional Component using Typescript.

Here's the rules.

**Typescript Functional Components**

- Function files must have a tsx suffix.
- In that tsx file:
 - Import the type of FC and perhaps UseState hook.

```typescript
// FC = Functional Component
import React, { FC, useState }
 from "react";
```
- Create a property prototype
```typescript
// allows HTML binding to a title property
type props = {
  title: string;
}; 
```
- Create the function

```typescript
const Test: FC<props> = ({ title }) => {
  const [hidden, setDisplay] = useState(false);
  function toggleVisibility() {
     hidden===true?setDisplay(false)
     :setDisplay(true);
  }

  return (
    <div>
      <h3 hidden={hidden}>{title}!</h3>
      <button onClick={toggleVisibility}>Toggle visibility</button>
    </div>
  );
};
```

Don't forget this part at the end of the file:

```typescript
// Makes it a module
export default Test;
```
**Consumer**
Import the component first:
```typescript
import Test from "./fileName";
```

Then use it like this:

```html
    <Test title="Yes it works!"></Test> 
```
For this simple example, we gain very little advantage for the effort. 

This is all we gain on the caller side if we're looking for properties.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1d0u87ci15n22gwgqtoq.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q9ewbjcytsuytx5142a1.png)

2.5 Stars for TSX

P.S.

- TSConfig.json should look similar to this:
```json
{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "strict": true,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "module": "es6",
        "moduleResolution": "node",
        "target": "es5",
        "allowJs": true,
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
    },
    "include": [
        "./src/**/*",
        "./src/public/**/*",
        "src/custom.d.ts"
    ]
}
```

JWP2021 TSX
A low-level entry point to get started contributing to open source.
Tags: frontend, beginners, opensource, hacktoberfest
Published: 2021-02-22 22:35:58

Hello,

Have you ever thought that opensource is for some kind of developer elite like Max Stoiber. And that it will take hours of investment to contribute?

Then you completely right 😆
But fortunately, not everybody needs to hit more then twenty thousand GitHub stars on their next open-source project like react-boilerplate did or to contribute with bugfixes and improvements for a complex project like React. 

During Hacktoberfest 2020 I used Chromes Lighthouse to identify and fix small comment problems like missing `alt="Happy hacking"` attributes on images or missing `rel="noreferrer"` on external links. Small problems that affect accessibility and safety.

These contributions were not innovative performance leak bugfixes for a million users framework or something in the same league. These fixes were not complex or time-consuming, but yet important and added value to the projects. Something the maintainers were truly happy for. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gip4i55xke4dq8d9jay9.png)

If you have never contributed to an open-source project before, the above method can be a low-level entry point that will get you're started without years of experience or hours of investment.

Happy Hacking
Troels Agergaard
The Open Source Community is quite literally the best
Tags: opensource, linux, audio, music
Published: 2021-02-22 22:31:22

I've had a seemingly obscure problem with PulseEffects where the active applications weren't showing, so I could not apply my settings to anything. Now, I'm quite bellyachey about my audio preferences, so this was (to me) a very annoying problem.

I've found someone on the Manjaro forums complaining of the same thing, where he linked the [issue](https://github.com/wwmm/pulseeffects/issues/794) he has raised on github. The solution was:
> pulseeffects started working again for no apparent reason 

Since this was not something I could continue with, I've commented with some details about my problem to see if maybe it can be solved.

Within 15 minutes I had a reply from both the developer and the guy who originally raised an issue, both of them pointing me towards possible solutions. I ultimately ended up solving the problem on my own, but without the pointers from them I'd most likely still be trying to find out what exactly is wrong.
Update the state in vanila React (without Hooks)
Published: 2021-02-22 22:27:11

I got this array of objects. I want to update the state with a button click

My array of object
...
constructor(props) {
     super(props)
     this.state = {
        players: [
           { number: null, points: null }
           ]
     }
  }
...
my update function:
...
onAddOneClick = () => {
    this.setState = ((state) => ({
     ...state, number: this.state.players.number,
     ...state, points: this.state.players.points + 1}
     )
     )
  } 
 ...
**number** i get from a input
...
onNumberEntered = (event) => {
      event.preventDefault();
      this.setState({number: event.target.value});
    }
...
I have unsuccessfully tried **console.log** to see if my updates code works. Can you help me and check if I did the right thing?

Thanks in advance
Regards
Peter
Day 314 : Lesson Learned
Tags: hiphop, code, coding, lifelongdev
Published: 2021-02-22 22:25:30

_liner notes_:
- Saturday : Radio show day! Did my laundry and some coding before the radio show. Had the show, had a great time. Did some post show editing and uploading work and went to sleep. The recording of this week's show is at https://kNOwBETTERHIPHOP.com

![Radio show episode image of photos of U-Roy and Prince Markie Dee who recently passed with the words Feb 20th 2021 Fled Cruz](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lzic7tzza27881vg2n0t.jpg)

- Sunday : Finally got an episode of "Attack on Titan" in. Did some post radio show promo work done. Did a little coding. Not sure where the day went. Next thing I knew, it was night time. haha Went to bed early since I had the live stream show the next morning.

- Professional : Had the live show in the morning. Then a meeting right afterwards, then another meeting after that. Had some lunch and then another meeting. haha. My brain is more fried after meetings than actually coding. haha

- Personal : Got up early so I could call the company I placed an order with a month ago to get an update before work. So apparently since I had them tap 4 holes, that would take 30-35 business days. Otherwise, would be like 10-12 days. I asked if I could just not get the holes drilled and I would figure something out. The operator said they would need to speak with a manager. Who knows how long that will take. Lesson learned. After work, my brain is fried. hahaha

![View of a green mountain range in Brecon, United Kingdom at sunset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lnxu6qwe8e955quo56g.jpg)

Going to go through some tracks for this week's radio show. I want to get a couple of screens done on the admin section for my side project. Plan on watching another episode of "Attack on Titan". We'll see.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube dy1dlm__GdY %}
100 Bytes Of Wisdom: Day 9
Tags: career, journey, advice
Published: 2021-02-22 22:03:50

---
title: 100 Bytes Of Wisdom: Day 9
published: true
description: Bytes of Wisdom is a new project by Sam Jarman that brings together snippets of advice for software engineers
tags: career, journey, advice
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewrugq9i3snglexftvig.png
---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewrugq9i3snglexftvig.png)

I've found that becoming proficient at multi-cursor editing, and making it a habit when faced with a repetitive text editing task will pay off greatly in the long run. Its something everyone, no matter how long they've been programming, should try to learn. Give it a go in your editor today.

Heads up: As with any terse bit of advice, there will be exceptions of course, and subtleties and nuance that can't possibly be captured in a Byte of Wisdom. This has been what I've experienced, I'd love to hear yours in the comments too!
Time to RIDEEE!!!!
Tags: beginners, javascript, bootcamp, firstyearincode
Published: 2021-02-22 21:54:26

# Davoris Cowell

### About Me

Hi! I'm from Georgia. I've been coding for four years now but there's never too much knowledge!

_Dublin, GA 31021._


## **Week 6**

_**WELCOME TO REACT!!!**_
We're starting react now! We started making our own _SPAs_. A SPA is also known as a **Single Page Application**. It loads a single document in a browser with _JS APIs_ and grabs data using HTTP request or the _fetch_ method.
**React** components use a render() method that takes input data and returns what to display.
Also whole receiving input data (this.props), a component can keep it's internal state data (this.state). When a component’s state data changes, the rendered markup will be updated by re-invoking render(). You can, using props and state, put together a small application that will track the current data as well as the text that the user has input.
**React** also lets us interface with other libraries and frameworks. And since it's written in _JS_, you can easily pass data through your app and keep state out of the DOM.


_**https://reactjs.org/**_
Check out MicroCosmos.JS: Experimental high-performance HTTP/2 API framework
Tags: javascript, node, http2, api
Published: 2021-02-22 21:42:36

Hello everyone!

MicroCosmos.js is a Proof of Concept HTTP/2 Node.js API framework. Right now, It supports automatic routing, params, server-sent events and it follows convention over configuration.

{% github microcosmos-org/microcosmos %}

In just few lines of code write API actions like this:
```javascript
export default class UserActions extends MicroAction {
  static get routeName() {
    return 'users';
  }

  show() {
    this.render.json({ message: 'Hello from /users/show' });
  }
}
```
Lib automatically initializes action stores from `actions/` folder in the root directory. You can map the action store by using static getter `routeName`, so in the preceding sample action `show()` will be mapped to https://localhost:3000/users/show.

Params
-

Params object can be accessed by using `this.params`, so if we need `urlSearchParams` we access it by `this.params.searchParams`.

Third part of the path is matched as id within params, so if we have path https://localhost:3000/users/show/42 we can access 42 by:

``` javascript
show() {
  this.params.id; // 42
}
```
On HTTP POST request we can access data object by using `this.params.data`.

```javascript
async create() {
  this.params.data; // {}
}
```

SSE
-

Microcosmos also supports Server-Sent Events, and those depend on Redis. If Redis has an additional configuration, it should be exported as an object from `conifg/redis.js` within a project.

To join SSE we use: `this.streamer.join('namespace', this.stream)` within Action Stores.
To Emit SSE we use: `this.streamer.emitEvent('namespace', data)`

```javascript
export default class UserActions extends ApplicationActions {
  static get routeName() {
    return 'users'
  }

  // Join for SSE
  joinEvent() {
    this.streamer.join('user_event', this.stream);
  }

  // Emit SSE
  emitEvent() {
    this.streamer.emitEvent('user_event', this.params.searchParams.get('event'));
    this.endTXT('ok');
  }
}
```

To listen for events for 'user_event' on client side you do:

```javascript
// chrome console
const event = new EventSource('/users/joinEvent');
event.onmessage = (event) => console.log(event.data);
```
and you can go to open https://localhost:3000/users/emitEvent?event=helloFromUserEvent in the new tab, and every time you hit this link it should output `"helloFromUserEvent"` in the console.
GitHub and Posting A REPO
Published: 2021-02-22 20:56:14

First I'll need to explain what GitHub is ...

Git is a version control system for developers to collaborate and keep track of their files while GitHub is a webservice where git projects are stored. Git handles source code management and GitHub is helpful for the developers of the software as well as the people using it. Developers can collaborate on software projects together on GitHub from anywhere.

What's a "repo" ...

"Repo" is short for repository. When you want to make different versions of a file to track its changes Git will put a .git folder within the root of your project. That .git folder is the git repo and it can keep track of your changes to the application your developing. 

I've made a tutorial below explaining how to commit files in a repo on github.
https://youtu.be/F-bQ_HYgOH8
What is React?
Tags: javascript, react, beginners, webdev
Published: 2021-02-22 20:50:48

What is React?

React is an open source front end JavaScript library for designing user-interfaces in Single Page Applications. 

An application in React is created by building separate components comprised of reusable HTML elements that can be dynamically rendered within the browser upon user action to create a seamless user experience similar to a native software application.

A React application is usually comprised of many small components which are loaded into one main App component to be displayed on the page.

Functional Components are basic JavaScript functions that are mainly used for rendering the user interface. They are sometimes called 'dumb' or 'stateless' components.

Hooks are a new feature introduced in React 16.8 that let you use state and other React features with function components without writing a class. 

Components are built up of smaller pieces called elements. Elements are rendered in the React DOM to create our webpages.
JavaScript Interview Question #19: Catching the rejected Promise
Tags: beginners, javascript, webdev, codenewbie
Published: 2021-02-22 20:43:39

![js-test-19](https://learn.coderslang.com/js-test-19.png)

Can you catch the Promise rejection in JS? Another unhandled rejection?	

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In JS, it’s impossible to catch the unhandled promise rejection using the regular `try/catch` blocks.

So, if the rejection does take place, then we’ll likely see a message like `UnhandledPromiseRejectionWarning …` or something along these lines.

Here, though, we don’t get to reject the promise properly.

JavaScript tries to evaluate the result of `null.length` which happens synchronously. An error `Cannot read property 'length' of null` will be thrown and caught in the `catch` block.

---

**ANSWER**: the error will be caught and the string `the error was caught! Cannot read property 'length' of null` will be logged to the screen.

[Learn Full Stack JavaScript](https://js.coderslang.com/sign-in)
Useful Django 3rd party packages Part 2
Tags: python, django, codenewbie, beginners
Published: 2021-02-22 20:33:04

###1- django-suit (not compatible with Django3)
this package is an alternative to Django's built-in admin interface, It comes with a lot of widgets and customizations.

Live Demo: http://djangosuit.com/admin/
Doc: https://django-suit.readthedocs.io/en/develop/
Source: https://github.com/darklow/django-suit


###2- django-import-export
this package is so helpful when you want to import or export your data, it supports multiple file formats (excel, json, csv, yaml, HTML, ...etc)

Doc: https://django-import-export.readthedocs.io/en/latest/
Source: https://github.com/django-import-export/django-import-export

###3- django-summernote
this package allows you to embed Summernote into Django (admin or form). and if you don't know Summernote, [Summernote](https://summernote.org/) is a JavaScript library that helps you create WYSIWYG editors online.

Doc: Not available (just use users guide on their repository)
Source: https://github.com/summernote/django-summernote


###4- django-storages
this is essential when your media files and your website and hosted on different servers, for example, your website is hosted on Heroku and your media files are hosted on AWS or Dropbox for example. Django comes with a storage backend for FileSystem just, so you have to use this library.

Doc: https://django-storages.readthedocs.io/en/latest/
Source: https://github.com/jschneier/django-storages


###5- django-allauth
[django-allauth](https://www.intenct.nl/projects/django-allauth/) is a reusable Django app that allows for both local and social authentication, with flows that just work.

Doc: https://django-allauth.readthedocs.io/en/latest/index.html
Source: https://github.com/pennersr/django-allauth
Tip for Python Devs: No more Googling
Tags: python
Published: 2021-02-22 20:18:19

A Helpful Tip for Python Devs.

help(): help is an inbuilt function which displays official documentation within Terminal.

Can be used in two ways:
1. By passing argument
2. within terminal

Stop Googling. Try help() method.

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">A Helpful Tip for Python Devs.<br><br>help(): help is an inbuilt function which displays official documentation within Terminal.<br><br>Can be used in two ways:<br>1. By passing argument<br>2. within terminal<br><br>Stop Googling. Try help() method.<a href="https://twitter.com/hashtag/Python?src=hash&amp;ref_src=twsrc%5Etfw">#Python</a> <a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> <a href="https://twitter.com/hashtag/100DaysOfMLCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfMLCode</a> <a href="https://twitter.com/hashtag/CodeNewbie?src=hash&amp;ref_src=twsrc%5Etfw">#CodeNewbie</a></p>&mdash; Abhishek Verma🇮🇳 (@w3Abhishek) <a href="https://twitter.com/w3Abhishek/status/1363944935439753218?ref_src=twsrc%5Etfw">February 22, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>