teleren/devto huggingface dataset:
A React Hook for universal routing
Tags: react, hook
Published: 2019-03-13 08:09:53

---
title: A React Hook for universal routing
published: true
description: A React Hook for universal routing
tags: reactjs, hook
---

I'm using `@reach/router` and love its simplicity.
But i love to use React Hook to get the page params and query string, so i make a simple hook for it.

Firstly, we need a `pageContext` for page component.

`pageContext.ts`:
```js
import React, { createContext } from 'react';

const pageContext = createContext({} as any);

export const withPageContext = (Component: any) => (props: any) => {
  return (
    <pageContext.Provider value={{...props}}>
      <Component {...props} />
    </pageContext.Provider>
  );
};

export default pageContext;
```
This also includes a HOC to inject `props` into pageComponent to be consumed with `useContext` hook later.

Second, we need to wrap this `pageContext.Provider` to all Route component:
`Route.tsx`:
```js
import React, { 
  FunctionComponent 
} from 'react';
import { 
  RouteComponentProps 
} from '@reach/router';
import {
  LoadableComponent
} from '@loadable/component';
import { withPageContext } from './pageContext';

type Props = { component: FunctionComponent | LoadableComponent<{}> } & RouteComponentProps;

const Route: FunctionComponent<Props> = ({ component, ...rest }) => {
  const Component = withPageContext(component);
  return (
    <Component {...rest} />
  );
};

export default Route;
```

And lastly, the thing we need, a `useRouter` hook:
`useRouter.ts`
```js
import pageContext from './pageContext';
import { useContext } from 'react';
import { parse, parseUrl } from 'query-string';
const isServer = typeof(window) === 'undefined';

const useRouter = () => {
  const { location, ...rest } = useContext(pageContext);
  const queryParams = isServer ?  
    parseUrl(location.pathname).query : 
    parse(location.search);

  const query = {
    ...queryParams,
    ...rest,
  };

  return { query };
};

export default useRouter;
```

Here, i mapped all `props` and `query string` into a `query` property returned by `useRouter` and we've done !

# Usage:

Firstly, declare your routes with our new `Route` component:

`App.tsx`:
```js
import React from 'react';
import Route from './Route';
import { 
  Router 
} from '@reach/router';
import loadable from '@loadable/component';

const User = loadable(() => import('components/User'));

const App = () => {
  return (
    <Router>      
      <Route component={User} path="/users/:userId" />
    </Router>
  );
};

export default App;

```

Secondly, use `useRouter` in our `User` component:

`User.tsx`:
```js
import React from 'react';

const User = () => {
  const { query } = useRouter();
  const { userId } = query;
  return <div>You requested {userId}</div>;
};
```

## Inspiration:
This is inspired by `react-router` and `nextjs`.
Article a day!?
Tags: motivation, learning, discuss, writing
Published: 2018-11-02 03:25:24

---
title: Article a day!?
published: true
description: You madman, I'll do it.
tags: motivation, learning, discuss, writing
series: November Daily
---

>Very quick idea. Would anyone else be up for trying to write a dev.to article a day during the rest of November?
 
Yes, I think I will. 

> This is, of course, a big cheat on my part because I'm counting this as my first one.

I am about to sleep, so me too. lol
Thinking out of the box
Tags: learning, puzzles
Published: 2018-11-06 21:51:36

---
title: Thinking out of the box
published: true
tags: learning, puzzles
cover_image: https://thepracticaldev.s3.amazonaws.com/i/yanwada2n4jqfmefqugx.jpg
---
We have all heard this sentence (or cliché?), but what does it mean?

According to old good friend wikipedia, it means to start thinking <b>differently</b> or <b>unconventionally</b> about some sort of problem, puzzle or whatever else. Simplified we should see it from other perspective. 

## Example!

I'll take a most common problem and i'm pretty sure you've already seen it.

<b>The problem:</b> "*connect the dots by drawing <b>four straight</b>, continuous lines that pass through each of the nine dots, and <b>never lifting the pencil from the paper.*</b>"

![ninedots](https://thepracticaldev.s3.amazonaws.com/i/fl3892j9yony316reu2v.png)

Okay, i see no problem in this, let's do it!

![ninedotsfilledwrong](https://thepracticaldev.s3.amazonaws.com/i/ftamfg960q1d488gjgrt.png)

Oh, that's wrong? Yeah, they are connected, but with FIVE straight lines and i need four. 

Ok, so i'll try another way! However, i don't want you to scroll five years, so we know that there is no way how to solve it with this method or might be?

## Solution!

So if we think about it out of box. We should end up with solution below.

![ninedotsfilledcorrectly](https://thepracticaldev.s3.amazonaws.com/i/o7qctguwfactg6zyugag.png)

And that's the solution. The interesting thing is that our brain automatically created an "imaginary square" that we cannot escape, but in the reality we <b>CAN</b>, because there is no rule telling us to stay in some kind of square.  

Btw can you find a solution(s) for this puzzle with same rules, but you can use only 3 straight lines?

## Other interesting puzzles

[Towers of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi)
Very well known [Rubik's Cube](https://en.wikipedia.org/wiki/Rubik%27s_Cube)
[Drawing](http://www.giftourprecious.com/wp-content/uploads/2017/10/Trace-The-Image-Brain-Teaser-Thinking-Outside-The-Box-Exercises.jpg)

## Conclusion

In my opinion this thing is connected with learning of anything, where you have plenty of ways how to solve the specific problem. It's very important to see other's work for our best improvements, everyone has a different style of thinking so we can collaborate why someone used this method and the other one used this one. 

### Thanks for reading

This is my first post and i hope you liked it just a little bit! If you can please leave a comment down below. I very appreciate any kind of critism especially for my writing skills and i know about my poor vocabulary.
3 coding habits to unblock yourself (Part 2)
Tags: errormessage, javascript, unblock
Published: 2018-11-08 22:26:05

---
title: 3 coding habits to unblock yourself (Part 2)
published: true
description: 
tags: #errormessage #javascript #unblock
---

Hello fellow coders.
welcome back to part 2 of some good habits to unblock yourself. If you missed the 1st part you can check it out right here: 
https://dev.to/trilemaestro92/3-coding-habits-to-unblock-yourself-part-1-9lg


Lets get started!

#ERROR REFERENCE

In part one I talked about console log and how it can help beginners like me see the errors and where they're located. In this article I will discuss the habit of learning error messages. 

JavaScript coding in particular is prone to errors due to its complex nature. Errors occur where you least expect them and they are one of the main cause of JS developer's banging their head in confusion. 

But fear not, I believe if you can build a habit of learning or even familiarizing yourself with some common error of JavaScript, this habit can help you unblock a bug or issue more efficient. 

In JavaScript there are many errors you can run across like ReferenceError, SyntaxError, RangeError, and many more. They all have different definitions and solutions. Therefore I would encourage you to start noticing some of the error code you are receiving and do a little research on them. Who knows once you come across the same error code more than once you can even built a radar for those error while coding and condition yourself to not make the same mistake.  

BTW you can check JavaScript error code all out here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors




## A few common JavaScript errors 

### Common SyntaxError: 

1. If errors: The “==” operator performs a comparison while the “=” operator assigns a value, very easy to mix up.
2. Mismatch brackets, case sensitive, overall spelling mistakes.

### Common TypeError : 

1.Using an Array method on non-Array object can cause an error to occurs, since you'll be calling a method on an undefined object. 

example.

![Alt text of image](https://thepracticaldev.s3.amazonaws.com/i/s8qgzvublwiiwhofhn6n.JPG)


*map method can only be used for Array not object*

2.Using **null** or **undefined** as an object. This is an error that occurs in browser when you read a property or call a method on a null or undefined object.




Those are some of common errors I've experienced. I'm certain in time my error list will grow as my knowledge on how to fix them. 

Hope this article was helpful. Part 3 coming soon!

Thanks for reading me!
Holding a loaded rifle without knowing it
Tags: productionmode
Published: 2018-12-08 23:18:46

---
title: Holding a loaded rifle without knowing it
published: true
description: Working in production mode needs extra care
cover_image: https://thepracticaldev.s3.amazonaws.com/i/29yuu2d3hcufg4cil9lk.jpeg
tags: production mode, 
---

Two stories:

1. When I've served in the army a not-so-funny story happened to one of my friends:
He played with his M16 because he was bored (It was the year 2000. no smartphones...). And in some weird way he ended up having his gun loaded without him knowing it.
So how do I know it?
Because an officer checked his gun... (lucky for us all).

2. When working with SQL SERVER a friend of mine (it's always friends. never me...) worked on his local copy of the database. 
Or that's what he thought he was doing.
Actually he had two tabs opened inside SSMS:
One representing his local enviroment. 
One representing our production.
Can you guess what happened?

You are probably right:
The production database was deleted.

Well let's just FF 3 hours later when all the managers came back from home because nothing worked. And although it was on SQL AZURE which has great backup, he somehow managed to do all the steps which avoids the normal way of restoring to point in time.

We were so helpless that we tried to restore the data from the cache into the DB!
Finally the guys from Azure came to our help and gave us what we needed.

What did I learn from this?
Seems like less then I thought.
Because yesterday it almost happened to me again!

It's so easy to get into these places.

The only way is DISCIPLINE.No fancy tool will save you if you don't use it.

You set rules, and you understand deeply why they exist (In some proffessions they say: "Regulations are written in blood").

Try not to hold a loaded rifle, and if you must hold it- at least be aware of it.
Technical debt is a good metaphor
Tags: programming, computerscience, softwareengineering
Published: 2018-11-12 21:13:13

---
title: Technical debt is a good metaphor
published: true
tags: programming,computerscience,software engineering
canonical_url: http://asawicki.info/news_1693_technical_debt_is_a_good_metaphor.html
---

There is this term " **technical debt**" used in the world of software development as a metaphor to describe poor quality of source code (or the lack of documentation, tests etc.), whether it's a bad overall architecture, quick and dirty hacks in some places, or any kinds of [software anti-patterns](https://en.wikipedia.org/wiki/Anti-pattern#Software_engineering). It makes the code harder, slower, and less pleasant to maintain, fix, and expand. It's called "debt" because, just as the financial debt, it causes some "interest" that needs to be paid, in form of increased maintenance cost and more bugs to fix, until it's repaid (refactoring or rewrite of bad code, completing work that was missing and left "TODO"). It is most frequently caused by lack of time due to deadlines imposed by business people - lack of time to fully understand the requirements and design good solution, to read and understand the existing codebase, to refactor or rewrite if the code is already bad.

Some people say that "technical debt" is a bad metaphor. There was this one article I can't find now which argued that bad code is unlike real-world debt because we don't need to pay "interest" until we actually need to go back to and modify the specific piece of code where we made a dirty hack. I don't agree with it. Sure things in software development are harder to measure and estimate quantitatively than in the business world, but I think that "technical debt" is a good metaphor. Just like in real life, there are different kinds of debt. It depends on who do you borrow money from:

- Leaving bad code in a place where you and everyone else in the team may never need to look again is like borrowing money from you family or best friend. You know the debt is there, but you may postpone paying it off indefinitely and you will still be fine.

- Leaving bad code in a place where you periodically need to make fixes and other changes is like borrowing money from a bank. You have to periodically pay interest until you repay it all.

- Finally, making ugly hack in a critical piece of code that you touch constantly is like being in so desperate need for money to borrow from mafia. You better repay it quickly or you will get in trouble.
Seventeen White dudes
Tags: discuss, agile, culture
Published: 2018-11-21 07:31:59

---
title: Seventeen White dudes
published: true
description: 
tags: discuss, agile, culture
---

This is quite a striking video. It's by a hero of mine Sarah Mei @sarahmei who writes all sorts of good stuff about agile and culture and software as well as other technical subjects.

https://www.youtube.com/watch?v=YL-6RCTywbc

It is a keynote she did where among other things she raises the challenge that a lot of agile practices are at least unintentionally exclusive and that if we don't fix the problems we can see that becomes intentionally exclusive. She lays out some of the issues about motivation, access and power dynamics in the office.  

I'd recommend watching the whole thing. However what I was pondering today was the key moment at about 18:16 when she puts up a slide of the signatories of the Agile Manifesto. It is literally seventeen white dudes, not that  radically dissimilar looking in age or appearance.

![Seventeen white guys in a grid](https://thepracticaldev.s3.amazonaws.com/i/zwtfxkbcxoho4gvhflwf.png)

I have wondered though how might Agile be different if a different, perhaps more diverse group of people had come together initially? 

I don't have any answers to this one yet. The team I'm on are a small group of quite different people from different cultures, split by geography and still figuring out how to do things. We are learning to be Agile together and there is probably lots we could do better.

What are other people's ideas of what a different more diverse agile might have looked like? 

It doesn't have to be based on reality. Creativity is fun. But it would be cheery to hear some stories of where people are either getting it right or getting it very wrong.
How do y'all patch other people's PRs in your local dev env?
Tags: discuss
Published: 2018-11-09 15:23:34

---
title: How do y'all patch other people's PRs in your local dev env?
published: true
description: Looking for advice on streamlining my workflow
tags: discuss
---

Scenario: you're assigned to review a pull request. It may have side-effects, so you want to build it locally to see it run for yourself. How do _you_ do that?

Here's what I do:
- From my local git client I run `git remote add <user> <git-url>`. This creates a new remote (eg "origin" or "upstream") corresponding to the PR author's fork.
- I create branch off of whatever the PR is merging into, usually "master".
- I pull in the changes from the remote branch, `git pull <user> <branch>` where `branch` corresponds to whatever is shown in the PR.

Now my client should be synced to the contents of the PR and we're off.

I don't like that workflow. Can I borrow yours? What do other people do in this scenario?

I've heard about appending `.patch` to the PR URLs to get a patch file, but not quite sure how to streamline that. Help!
3 Little Known But Useful Vim Tips
Tags: vim, masteringvimquickly
Published: 2018-11-26 15:35:05

---
title: 3 Little Known But Useful Vim Tips
published: true
description: Vim tips from Mastering Vim Quickly book
tags: vim, mastering vim quickly
---


I'll show you three tips which can be incredibly useful, yet, they are very little known.

---

## Tip #1 - Open/edit/save archives

Running a command like:

```
$ vim archive.tar.gz
```

will open the `archive.tar.gz`, and list the contents of the archive. From there, you can open, edit and save changes in these files, without the need to extract them first.

How cool is that? :)

Supported archives: tar.gz, tgz, zip, jar, etc.


## Tip #2 - Edit files remotely

Vim has the ability to edit files remotely, over the network. This feature comes with the netrw plugin. To achieve this, `netrw` uses the SSH protocol, and manages remote files via the `scp` command.

Here's how to do it:

```
vim scp://user@myserver[:port]//path/to/file.txt
```

Note the double `/` for the directory on the remote host, which is needed to correctly resolve the absolute path. `[:port]` is optional.

So with the command above you can open a file located on a remote host for editing.

What actually happens in the background is that Vim uses `scp` to download the requested file from a remote machine to a local `/tmp` directory, and then opens it for editing. 

When you save your changes to the file, the changes are first applied to a local copy in `/tmp` directory. After that, the file is uploaded via `scp` to the remote host.



## Tip #3 - Magic

Did you know that you can open the last edited file on the machine with cursor on the latest location?

Just start Vim, hit `Ctrl`+`o`+`o` - and there you go.

Keep hitting `o` and see what happens ;)


---

Now, if you wanna discover more Vim tips you've never heard of, take a look at my book [Mastering Vim Quickly: From WTF to OMG in no time](http://jovicailic.org/mastering-vim-quickly/)
Game Off 2018 (4)
Tags: lua, gamedev, gameoff2018, pixelart
Published: 2018-11-09 20:17:07

---
title: Game Off 2018 (4)
published: true
description: Edition of the map and some animation for the flower!
tags: lua, gamedev, gameoff2018, pixelart
---

Hello!
It's the week, so I don't really have the time to work on new things. So I've work on the player mouvevement and on the player design!

![World](https://thepracticaldev.s3.amazonaws.com/i/4lkyuplggeu9zxj3xji5.gif)

It's all, sorry, with my studies I don't really have the time.

Have a nice day!
It is really hard for me to ship daily.
Tags: discuss
Published: 2018-11-11 08:08:49

this post was also lost in the middle of writing it -.- it was about 5 paragraphs this time and I am really bent out of shape about it. I guess I am going to start writing these in VSCode and then pasting them over.... GRRRRR.

To summarize. I am doing this challenge to get in the habit of shipping daily. I am doing this in preparation for some upcoming products I will be launching, all of which will be learning material to aid in my one-on-one mentoring I currently offer.

I believe shipping is a skill, and I am bad at it. I want to be better at shipping all the things! I think doing daily blog posts will make me better at shipping code daily.

Shipping code daily was easy when it was behind corporate walls, now that its public its spooky. But I can't let my skills dull, and I need to get my learning resources out and in the hands of the public, so I am pressing forward trying to finish my site for private mentoring along with some course content to go along with it. 

I think its working so far, and I really enjoy writing these posts, no matter how silly they are. I don't like the deleting part... maybe I should see if that is an issue I can resolve.
(Update #2) Just a prototype game.
Tags: gamedev
Published: 2018-11-11 11:17:16

---
title: (Update #2) Just a prototype game.
published: true
description: 
tags: gamedev
---
Hey everyone! 

These days I did some coding on my game and had a little progress. I have added some obstacles(a crate as a placeholder) for limiting the player's area of movement. What you think of?

{% youtube Gj3LyzVVWzY %}

Until next time! Cheers.
Magento 2 Promotion Banners
Tags: magento2, magento, magento2promo, magento2discount
Published: 2018-11-11 17:35:41

---
title: Magento 2 Promotion Banners
published: true
description: 
tags: #magento2 #magento #magento2promo #magento2discount
---


<p>The <a href="https://www.ulmod.com/promotion-banners-for-magento-2.html">Promotion Banners for Magento 2</a> allows creating any number of promo banners to let shoppers be aware of all discounts and deals you offers. Bunch of features included such as ten predefined positions, flexible banners and bars placement, display multiple banners in an attractive slider, responsive to mobile devices, restrict promotions display, support multiple websites, stores, and store views, multiple customization options, and more.</p>

<p>Check more details here : <a href="https://www.ulmod.com/promotion-banners-for-magento-2.html">https://www.ulmod.com/promotion-banners-for-magento-2.html</a></p>
Beer vs coffee?
Tags: discuss, devdiscuss, devtips, remoteworkingtips
Published: 2018-11-12 16:30:37

---
title: Beer vs coffee?
published: true
description: What makes you more productive? Beer or coffee?
tags: #discuss #devdiscuss #devtips #remoteworkingtips
---

Say it's 12:00 AM and you still need to complete that last feature before the sun rises in a few hours. You decided to grab something to drink so you went to your kitchen and you were presented by two options:

1. Ice-cold BEER.
2. Brewed COFFEE.

What will you grab?

I just recently tried beer and it works well for me. Just drink enough. LOL
Abstracting IO using F#
Tags: f, softwareengineering, distributedsystems
Published: 2018-11-13 01:41:56

---
title: Abstracting IO using F#
published: true
description: In this post, I discuss approaches to unifying IO access pattern in F#. Unification allows us to abstract the underlying infrastructure implementations while enabling us to have consistent interfaces for all our IO patterns. Having shared access methods enabled consistent wrappings for things like retries, metrics, logging.
tags: F#, Software Engineering, Distributed Systems
---

In this post, I discuss approaches to unifying IO access pattern in F#. Unification allows us to abstract the underlying infrastructure implementations while enabling us to have consistent interfaces for all our IO patterns. Having shared access methods enabled consistent wrappings for things like retries, metrics, logging.

[To Read More](https://medium.com/jettech/abstracting-io-using-f-dc841519610e)
New Video Course To Build a DEX, Metamask Privacy Mode | EatTheBlocks Newsletter #15
Tags: dex, ethereum, dapps, metamask
Published: 2018-11-13 08:25:57

---
title: New Video Course To Build a DEX, Metamask Privacy Mode | EatTheBlocks Newsletter #15
published: true
description: 
tags: DEX, Ethereum, Dapps, Metamask
---

![](https://thepracticaldev.s3.amazonaws.com/i/b34sk2d7136dj3832m6n.png)

This week in the EatTheBlocks newsletter: New Video Course To Build a DEX, Metamask Privacy Mode, and more!

Post:  https://eattheblocks.com/eattheblocks-newsletter-15-new-video-course-to-build-a-dex-metamask-privacy-mode/
Video: https://youtu.be/jG8gf0htMIo

If you are a developer interested in learning about Dapp development, Solidity, Truffle, Web3, Ethereum protocol, Token standards ..., you will love this newsletter! Every week I send the 10 MOST INTERESTING tutorials, tips & news for Ethereum Dapp developers