teleren/devto huggingface dataset:
A React state hook for computed values
Tags: react, typescript, javascript
Published: 2019-08-29 13:31:10

Hooks are great!

But I found myself writing a lot of `useState` with `useMemo` for having computed fields for every state.

Let's look at an example. 

Say I have this component:
```tsx
const Component = () => {
  const [num, setNum] = useState(0);

  return (
    <div>
      <button onClick={() => setNum(num + 1)}>Inc</button>
      <button onClick={() => setNum(num - 1)}>Dec</button>
      <span>{num}</span>
    </div>
  );
}
```

And I want to display if the number is even or not and the number multiplied by 10.

So I'll do:
```tsx
const Component = () => {
  const [num, setNum] = useState(0);
  const isEven = useMemo(() => num % 2 === 0, [num]);
  const multiplied = useMemo(() => num * 10, [num]);

  return (
    <div>
      <button onClick={() => setNum(num + 1)}>Inc</button>
      <button onClick={() => setNum(num - 1)}>Dec</button>
      <span>{num}</span>
      <span>isEven: {isEven}</span>
      <span>by 10: {multiplied}</span>
    </div>
  );
}
```

This is not bad, but obviously this is rarely the case.
Usually, these mapper functions add up and your state is more complicated than that.
You end up with a lot of map functions and it all gets really messy!

So we can wrap it all with a simple custom hook that gets an initial value and an unlimited list of map functions -
```jsx
function useMappedState(initialState, ...mapFns) {
  const [state, setState] = useState(initialState);

  const memo = useMemo(() => mapFns.map(mapFn => mapFn(state)), [state]);

  return [state, setState, memo];
}
```

### Typescript

It gets really complicated with Typescript though, how can you get an unlimited number of map functions and get their return type applied for each destructured value?

Of course, you can use function overloads for each added map function, but you end up working for your types. (and I hate working for my types)

[Typescript Mapped types](https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types) to the rescue - lets us iterate over each map function and get back the return type, we can dive into it, but this is for another post.

This is how it looks like
```ts
// types:  number       Dispatch...      boolean     string
const [    number   ,    setNumber   , [ isEven , numberName ]] = useMappedState(
  initialValue,
  value => value % 2,
  value => value + 'name'
)
```

I've just published [use-mapped-state](https://github.com/EladBezalel/use-mapped-state), give it a go and let me hear your thoughts! :D

EDIT: As requested, I'll create another post talking more about the encountered problem with typescript, how I solved it and what I learned about it 

P.S. Credit for @Yoav for the prototype and the name
My experience at andela prebootcamp workshop
Tags: webdev
Published: 2019-08-29 12:54:21

Hello, my name is Mutangana Edgar, I attended the andela prebootcamp workshop of circle 10; and it help me alot with making the adc standardized in pivotal tracker,github workflow,css,js,node,express and postgres. Apart of the prebootcamp there was non technical skills which I also learned, growth mindset,seeking feedback, asking questions and many more other skills. I want to end this short paragraph by thanking all those who prepared this workshop.
Do you make your SVG using code? or using software?
Tags: discuss, svg, design
Published: 2019-08-29 12:32:47

---
title: Do you make your SVG using code? or using software?
published: true
description: How do you make your SVG images? What is your process?
tags: discuss, svg, design
---

I am very new to the design world and I find websites such as [Splitwise](https://www.splitwise.com/) fascinating! 

Now I want to dip my toe's in but I want to know. For more complex SVG's what do you use to build them? what is your process?
#CodepenChallenge SVG Polygon Tree: Home Page Parallax Design
Tags: codepen, vue, design, javascript
Published: 2019-08-29 12:31:34

<p>My challenge for this week, parallax design for a home page.</p>

<p>Parallax functionality is coded using VueJS.</p>

{% codepen https://codepen.io/takaneichinose/pen/RwbgKqd %}
On Readability
Tags: readability, programmingtips, javascript, programming
Published: 2019-08-30 06:42:57

---
title: On Readability
published: true
tags: readability,programming-tips,javascript,programming
canonical_url: https://medium.com/@hazterisk/on-readability-b9fbeb97b46e
---

None of this is new and I don’t know that it’s possible to follow these 100%. But if these are your targets then your code will be a pleasure to work with.

### The Function Does Not Rely on Hidden Cleverness

Language peculiarities around order of interpretation for type coercion are confusing. Yes it’s fun to explore them, but leveraging them in production is effectively setting a landmine for the next developer who touches that code.

![](https://cdn-images-1.medium.com/max/828/1*R7aLiky3T7mArMRCxwQ3zw.png)<figcaption>Javascript favorite language comic</figcaption>

### The Function Makes Sense in Isolation

The reasons why a function was constructed are apparent from the title and contents of the function, without the need for additional context of the caller or any internally called functions.

If a developer needs to read anything other than the function to understand what it’s doing, it’s not readable. The ultimate first prize is to convey precise meaning with the function name alone.

### The Function Assumes Knowledge of the Language

Yes the semantics of Promises and methods like .reduce are cumbersome. Yes closure and context take effort to initially get your head around. Yes you still need to be comfortable with all of that.

The one caveat here is to be careful not to fall into leveraging hidden cleverness.

### Consistency Trumps Comfort

So much of bug reduction boils down to eliminating surprises. If you join a front end team of ex-backend devs who are all writing functions like this:

```
function makeThingsHappen()
{
  // things happening
}
```

or they’re using / not using semicolons, or they’re using spaces / tabs, or [insert your pet peeve here], just bite the bullet and join in. Get some auto-formatting and let go of your petty preferences, they truly do not matter. Your ability to become comfortable in environments that go against your personal preferences is a professional quality — develop it.
Awesome Animation Checkbox CSS Toggle - Day / Night Mode
Tags: codepen, javascript, html, css
Published: 2019-08-29 11:48:07


---
title: Awesome Animation Checkbox CSS Toggle - Day / Night Mode
published: true
tags: codepen, javascript, html, css
---

{% codepen https://codepen.io/ahmadbassamemran/pen/yLBXBmy %}


<hr/>
[Do Not Forget To Like & Subscribe In The Channel:](https://www.youtube.com/AhmadEmran?sub_confirmation=1)
<hr/>


{% youtube y6jtDY0yrZw%}
The most used database engine x Blockchain
Tags: sqlite, sql, blockchain, iot
Published: 2019-08-29 11:19:57

Did you know?

SQLite is the most used database engine in the world. There are over 1 trillion  SQLite databases in active use. SQLite is built into all mobile phones and most computers and comes bundled inside countless other applications that people use every day. Some well-Known users of SQLite are Apple, Adobe, Bosch, Bently, Google and Microsoft.

SQLite is not a "Lite" version of SQL, SQLite is full-featured SQL implementation. In contrast to many other database management systems, SQLite is not a client–server database engine. Rather, it is embedded into the end program.

Now, imagine making this programming language compatible with blockchain!

A hybrid blockchain project, Aergo is making this possible. They created a variation of SQLite that makes it compatible with blockchain. The project dubbed AergoLite, brings blockchain compatibility to billions of devices using SQLite. By pushing data to a blockchain instead of a centralized server,  new use cases are made possible. Securing IoT devices is made possible without investing in very expensive infrastructures. This will open opportunities for businesses and developers in producing smart factories, smart grids and self-driving cars to name the few.

Here is a presentation of Aergo CEO Phil Zamani:
https://youtu.be/_eDH0pJ4GL0

If you are interested, you may visit their website:

SQLite website: https://www.sqlite.org/about.html
Aergo website: https://www.aergo.io/
Template File Processing in Go
Tags: tutorial, go, templates
Published: 2019-08-29 10:35:03

---
title: Template File Processing in Go
published: true
description: 
tags: tutorial, go, templates
cover_image: https://thepracticaldev.s3.amazonaws.com/i/p1cejdzuzdt31zl8wt8d.png
---

In a [previous post](https://dev.to/kirklewis/go-text-template-processing-181d) I demonstrated how to get a Go template's interpolated string result. However, if you just want to interpolate and then write the string result straight to file, this post demonstrates how.

## The Template File
The following text can be saved to a file `templates/greeting.tmpl`. 
```go
{{.Greeting}} {{.Name}}!
```
The template string above contains two annotations `.Greeting` and `.Name` which is enough for this demonstration.

## Execute and Write
The first argument of the `text/template` package's `Execute` function uses an [io.Writer](https://golang.org/pkg/io/#Writer) interface. As such, if we pass this argument an `os.File`, its [write](https://github.com/golang/go/blob/fa02af4238a3d41e23bc945e7d48e50fe4429405/src/os/file.go#L145) function will be used to write the processed template bytes straight to file.

Add the following code to a file named `process-file.go` .

```go
package main

import (
    "os"
    "text/template"
)

func main() {
    // variables
    vars := make(map[string]interface{})
    vars["Greeting"] = "Hello"
    vars["Name"] = "Dev"

    // parse the template
    tmpl, _ := template.ParseFiles("templates/greeting.tmpl")

    // create a new file
    file, _ := os.Create("greeting.txt")
    defer file.Close()

    // apply the template to the vars map and write the result to file.
    tmpl.Execute(file, vars)
}
```
_For brevity, I have omitted error checking in the code above by using an underscore_

**Run the file**
```bash
go run process-file.go
```

Running the line above should create a file named `greeting.txt`. Check the contents of this file.


```bash
cat greeting.txt

Hello Dev!
```

Thank you for reading! The code used in this post can be found as a Github gist [here](https://gist.github.com/kirklewis/e502c234fe6e88137544762dc419c644).
Introduction to Docker Part 5
Tags: docker, ubuntu, digitalocean
Published: 2019-08-29 10:03:56

Checkout Part 5 of my quick introduction to Docker blog posts! 

This is going to be the last part of the series and I'll show you how to setup and work with Docker #Swarm mode. 

I'll be doing some hands one demos with 6 @digitalocean #Ubuntu #servers:

https://bobbyiliev.com/blog/introduction-to-docker-part-5

Let me know if you have any questions!
SOLID Microservice?
Tags: discuss, microservices, solid
Published: 2019-08-29 09:45:08

---
title: SOLID Microservice?
published: true
description: thoughts on microservice
tags: discuss, microservice, SOLID
---

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

If a web api can be considered equivalent to an OOP class, a microservice can be considered as a class written maintaining SOLID principles.

Microservice is not a magic, but a well-designed service component serves specific responsibilities with other components.

Like a class maintaining Single Responsibility Principle (SRP) helps on maintainability and extensibility, the modular nature of microservice makes a huge difference in different size of projects.

Your thoughts?
How to validate your startup idea in 1 week
Tags: nocode, freetemplates, webdev, startup
Published: 2019-08-29 09:20:37

---
title: How to validate your startup idea in 1 week
published: true
description: 
tags: no-code,freetemplates, webdevelopment,startup
---
So, you’ve just had a brilliant idea for a game-changing new product. Your palms are shaking with excitement. You can’t think of anything else but getting this thing into the world as fast as possible.
Alright, easy there tiger. Inspiration is an artist’s game, but it’s not the way to build a startup. You’ve got a spark, but like it or not, as Lenny Manor says, your idea sucks until proven otherwise.
The good news is that there are tried and tested ways of proving your idea doesn’t suck. You can, if you’re lucky and focused, validate your startup idea in 1 week.
Sounds crazy? It really isn’t — you always want to validate as soon as possible, otherwise you may end up burning a lot of resources and losing a lot of time. We’ve been there and done that — [read more about our experience...](https://blog.zeroqode.com/how-to-validate-your-startup-idea-in-1-week-149726b3b536)
Walking into a bar
Tags: jokes
Published: 2019-08-29 08:32:43

---
title: Walking into a bar 
published: true
description: It's a classic. Not sure who originally wrote it to be honest!
tags: jokes
---

A test engineer walks into a bar, bars, 5555, ;:&£433, 😂🙂🤷‍♂️, OR 1= 1; DROP TABLES; and orders a pint, pints, 66766
How I get productive when I am tired like s#*t
Tags: productivity
Published: 2019-08-29 08:15:22

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

- **Set a timer for each tasks**
Basically pomodoro the s#*t out of every thing I do. I will then know how long each kind of task takes and better prioritize my work the day after.

- **Take a Break**
I love to take breaks between each tasks. After a small achievement I pat myself on the back and get myself a new cup of hot coffee. 
Don’t struggle for two hours,  and achieved on a little, when you can rest and get more done in the next hour. 

- **Start Small**
This always works for me. Whose brain can function well in the morning? Still feeling sleepy, I will start with the little things, check off the small tasks on the [to do list](https://quire.io/compare/best-to-do-list-apps) first that doesn't need my brain working on a high functioning level. 


- **Personal little tip**
I like to absorb some sunlight before I start working. I don't know why this works for me. Normally, I stand in front of the window with the sunlight hitting my face, eyes closed, with a cup of coffee in my hand. After a few minutes, I will feel refreshed and ready to work. I know, I know, it sounds a little bit stupid, but I recommend give it a try.
waybackmachine August '19
Tags: waybackmachine, monthly, playmoss
Published: 2019-08-29 08:10:20

> ... because it's always fun to go back in time and remember how it was back then ...

---

# pet-project :: Playmoss playlist downloader

Yeah! Finally had my hands on some code in order to download my playlists from [Playmoss](http://playmoss.com) :)

Python is not my first language, don't judge me...

{% gist https://gist.github.com/wideawakening/4d7afd8878ca6bac297d99a68cd516e2 %}

---

# a pic :: The league of heroic Software Developers


![The league of heroic Software Developers](https://i.imgur.com/B2Mm9R8.png)

from [League of heroic Software Developers](https://neilonsoftware.com/heroic-software-developers/). I would say I'm quite a shapeshifter mechanic but guess what my teammates say x)


---

# remote-ergonomics :: SafeEye for an eye resting programme

Something that still happens me, both working at office or home, is that if I'm focused on something I tend not to make breaks, and this app has helped me to at least, exercise my [SafeEyes](http://slgobinath.github.io/SafeEyes)

I'm still looking forward to something similar, but related to hand/leg/back exercises.


---

# watch :: Silver Bullet Syndrom

{% youtube 3wyd6J3yjcs %}

---

# adopt :: Java 11 Scripting

Although I'm starting to get my hands on python and would like to get more comfortable with bash scripting. Knowing that at some point I can use [java11-Scripting](https://www.infoq.com/articles/single-file-execution-java11) is an interesting concept for devops tooling

---

# The w00t? :: The Ikea Effect

While I was reading about [How to break the monolith into microservices](https://martinfowler.com/articles/break-monolith-into-microservices.html) I got to this part
>  The labor of building, no matter how painful the process or imperfect the result, make us grow love for it. This is in fact known as the IKEA Effect. 
 
---

# takemymoney :: AirSelfie
> The smallest, easiest, and most ejoyable aerial camera ever.
{% youtube eohR1rkUO-c %}


---

# a game :: SuperHexagon

Monthly hook on this game called [SuperHexagon](https://store.steampowered.com/app/221640/Super_Hexagon/) (round 2€ in steam), it's like being on drugs :D
The mechanics is quite simple, just gonna zen your mind, see the shape, and the music will show you.... the crazyness; why lie.

If you enjoy live-time puzzles and precision-requiring repetitive-games to chill a bit, should try it!

{% youtube X_HH5YkeMOs %}

---

# monthly ear hook :: DDR Stardom Shuffle Songs

From the OST of [DDR Stardom Shuffle](https://www.youtube.com/results?search_query=ddr+stardom+shuffle)

{% soundcloud https://soundcloud.com/alden-tang-simply-allen/dr-stardom-crazy-shuffle-yooh %}
NodeJS: How To Create Your Own Module
Tags: javascript, node, eli5
Published: 2019-08-29 08:06:48

---
title: NodeJS: How To Create Your Own Module
published: true
description: NodeJS: How To Create Your Own Module
tags: javascript, node, eli5
series: Intro to NodeJS
---

## Intro

So we [installed NodeJS](https://dev.to/miku86/what-is-nodejs-how-to-install-it-1900) on our machine.

Now we want to learn how to create our own [module](https://nodejs.org/api/modules.html).

## Write a simple script

- Open your terminal
- Create a file named `logger.js`:

```sh
touch logger.js
```

- Add this JavaScript code into it:

```js
// the function should get a message type and a message
function logger(type, message) {
  let format;

  // different message for different message type
  switch (type) {
    case 'error':
      format = `[ERROR] ${message}`;
      break;
    case 'success':
      format = `[SUCCESS] ${message}`;
      break;
    default:
      format = `${message}`;
      break;
  }

  console.log(format);
}

// export the function using object property shorthand syntax
// to rename, use "newName: logger"
module.exports = { 
  logger
};
```

Note: For the sake of simplicity, this example is very lightweight, has no error/edge-case handling (e.g. no type), no separate file for the message types, no colors etc.

---

## Write a second simple script

- Open your terminal
- Create a file named `index.js`:

```sh
touch index.js
```

- Add this JavaScript code into it:

```js
// import the exported logger property
const { logger } = require('./logger.js');

// use the function
logger('error', 'This is an error message.');
logger('success', 'This is a success message');
```


## Run it from the terminal

- Run it: 

```sh
node index.js
```

- Result: 

```
[ERROR] This is an error message.
[SUCCESS] This is a success message.
```

---

## Next Steps

- Q: What happens, when you forget to add a `type`? How can you solve this?
- Q: How can you improve this example by separating the message types into a constant?
- Q: How can you improve this example by using an object as parameter instead of two strings?
- Q: Do you need some additional error handling? (=> Docs)

---

## Further Reading

- [Modules](https://nodejs.org/api/modules.html)
- [module.exports](https://nodejs.org/api/modules.html#modules_module_exports)
- [exports shortcut](https://nodejs.org/api/modules.html#modules_exports_shortcut)

---

## Questions

- What is your favorite self-written module, that improves your developer life?
Java program to check palindrome string using recursion
Tags: javaprograms, palindromestring
Published: 2019-08-29 07:11:08

How to check if a string is a palindrome in java using recursion in java is the most common java interview question.

Recursion means a function calling itself. In this java program first “checkPalindrome()” method with String parameter “str” is created.

This method first checks if user entered string length is 0 or 1 using if statement. Here, if string length is equal to 0 or 1 then string is palindrome.

import java.util.Scanner;
public class RecursivePalindromeJava 
{
   public static boolean checkPalindrome(String str)
   {
      if(str.length() == 0 || str.length() == 1)
         return true; 
      if(str.charAt(0) == str.charAt(str.length() - 1))
         return checkPalindrome(str.substring(1, str.length() - 1));
      return false;
   }
   public static void main(String[]args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string : ");
      String strInput = sc.nextLine();
      if(checkPalindrome(strInput))
      {
         System.out.println(strInput + " is palindrome");
      }
      else
      {
         System.out.println(strInput + " not a palindrome");
      }
      sc.close();
   }
}


Output:

Please enter a string : mom
mom is palindrome.
Oh snap, here comes *another* JavaScript framework | SVELTE 
Tags: javascript, webdev, svelte, framework
Published: 2019-08-29 07:02:04

---
title: Oh snap, here comes *another* JavaScript framework | SVELTE 
published: true
description: There’s a new frontend framework soaking up the spotlight called Svelte. Is it a fad or is it the future of web development?
tags: javascript, webdev, svelte, framework
---

###We all knew this day was coming in the frontend framework wars. 

Svelte is a radical new approach to building user interfaces. Whereas frameworks like React & Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.

Rather than applying techniques like virtual DOM diffing, Svelte writes code that surgically updates the DOM when the state of your app changes.

***

_This video originally appeared on www.youtube.com/realtoughcandy_.
Come follow me there!
Is there a official recommendation for the access token and refresh token life time?
Tags: refreshtoken, accesstoken, api, rest
Published: 2019-08-29 06:19:30

---
title: Is there a official recommendation for the access token and refresh token life time?
published: true
description: 
tags: Refresh Token, Access Token, API, REST
---
Just a question that I never found an answer to it so far.
How to Use Gatsby With PHP
Tags: php, gatsby, discuss
Published: 2019-08-29 05:49:56

---
title: How to Use Gatsby With PHP
published: true
description: Can anyone help how to build a PHP website with Gatsby?
tags: Php, Gatsby, Discuss
---
Hello all, I found Gatsby is very awesome, I am not much familiar with javascript. I have built a website with Php. Can anyone help how to build a PHP website with Gatsby?