teleren/devto huggingface dataset:
Creating a Storybook Lerna package
Published: 2021-03-11 16:56:52

---
title: Creating a Storybook Lerna package
published: true
description: This exercise showcases how to create a Storybook Lerna Package
tags: 
cover_image: https://comicvine1.cbsistatic.com/uploads/original/12/125570/3811010-7810377648-Blood.jpg
---

# Setup

I'm writing this assuming you have knowledge and familiarity with setting up Lerna. Also, the scenario here is assuming you have a bunch of reusable components in their own dedicated package. Let me know if you have questions on steps that I cover at a high level.

## Setup checklist

### Repo is setup
`mkdir superDuperRepo`
`git init`
`git add .`

### Lerna as a dev dependency
`yarn init`
`yarn add lerna --dev`
`lerna init`

### lerna.json
```
// superDuperRepo/lerna.json

{
  "packages": [
    "packages/*"
  ],
  "version": "independent",
  "npmClient": "yarn",
  "useWorkspaces": true
}

```

### package.json
```
// superDuperRepo/package.json

{
  "name": "superDuperRepo",
  "private": true,
  "workspaces": [
    "packages/*"
  ]
}
```

### Drop reusable components in their own package
`superDuperRepo/packages/reusableComponents`

### Add storybook as a package
`lerna create storybook`
`cd packages/storybook`
`npx sb init` // delete boilerplate stories
`yarn add react`
`yarn add react-dom`

### Yarn workspaces
`yarn config set workspaces-experimental true`


### Add reusable components package to the storybook package
`lerna add landing --scope=storybook --dev`

### Resolving reusable components package files
```
// superDuperRepo/packages/storybook/.storybook/webpack.config.js

const path = require("path")

module.exports = ({ config }) => {
  // a bunch of other rules here

  config.resolve.modules = [
    path.resolve(__dirname, "..", "..", "reusableComponents", "src"),
    "node_modules",
  ]

  /*
  // Alternately, for an alias:
  config.resolve.alias: {
    "@styles": path.resolve(__dirname, "..", "src", "styles")
  }
   */

  return config
}
```
### Creating the story

```
// superDuperRepo/packages/storybook/stories/Button.stories.jsx

import React from 'react'
import Button from 'reusableComponents/src/Button'

export default {
  component: Button,
  title: 'Reusable Components/Button',
}

const Template = args => <Button {...args} />

export const Default = Template.bind({})

Default.args = {
  title: 'Submit'
}

```

### Run Storybook
`yarn storybook`

### Conclusion
At this point you should be able to run storybook and view the single story (especially if you deleted the boilerplate stories). It'd be lovely if there was an automated way of creating stories for all the components that I have. Still trying to figure that one out. 

### Helpful troubleshooting notes
`lerna list`
`lerna bootstrap`
`lerna link`
`lerna changed`
`yarn workspaces info`
I am new here!
Tags: gamedev, webdev, javascript, html
Published: 2021-03-11 16:51:43

Hey it's the same guy from Repl.it and YouTube coming to you on DEV. It's none other than CoderBroDev. Join me as we look into my projects with devlogs, write awesome tutorials and also host a ton of podcasts every Friday. I will also be sharing a weekly update on my STEAM release- A Glitched Ball.
I will occasionally give advice and comment on various projects as well. 
I am a Game Developer and Web Designer currently hosting a new learning club called CodeCloud and one of the scripting developers at Freshclass- CSS Redefined.
Currying in JavaScript
Tags: javascript, beginners
Published: 2021-03-11 16:44:08

In JavaScript a function with multiple arguments can be broken into a series of interconnected functions where each function returns a new arrow function that accepts a single argument. It goes on until the arguments are finished so a 3 argument function can have a function inside it returning another function taking up one argument each.

Currying can be achieved with only those function that accepts multiple argument else not.


A normal function would look like below 

```
function sum(x,y,z){
  return x+y+z;
}

sum(2,3,4)
>9

```

Now let's see how the same function would look like while curried

```
function sum(x){
  return (y) => {
    return (z) => {
      return x+y+z;
    }
  }
}

sum(2)(3)(4)
> 9
```
The last function that is returned has access to the outer function scope (closure feature) hence it can easily get the values of x and y and return the sum with z. 

Currying is useful in those scenarios where a function accepts multiple arguments where one or two argument are constant on every function call i.e their value stays the same. In that scenario we can use currying and reduce the effort of passing the constant argument in each function call.

Suppose a function fx is having a formula x + y + z + c where c is constant say €25 for every function call but the other values changes everytime. Then we can write like below:


```
function fx(x){
  return (y) => {
    return (z) => {
      return (c) => {
        return x+y+z+c;
      }
    }
  }
}

const simplifyFX = fx(25);
simplifyFX(1)(2)(3)
>31

```
We can use lodash library to curry function on the fly. 

```
var a = function (x,y,z){
  return x+y*z;
}

var curryMe = _.curry(a);
var net =  curryMe(5);

net(2,3);
>11
net(2)(2);
>9
net(2,3,4)
>11
```

We can also achieve currying using bind on the above function.

```
var net2 = a.bind(this, 5)
net2(2,3)
>11
```
Run Node.js scripts from under a TOR / HTTP proxy
Tags: javascript, docker, tor, proxy
Published: 2021-03-11 16:16:42

### Requirements:

- [Node.js](https://nodejs.org/) using [`got`](https://github.com/sindresorhus/got/#readme), [`socks-proxy-agent`](https://github.com/TooTallNate/node-socks-proxy-agent), and [`cross-spawn`](https://github.com/moxystudio/node-cross-spawn#readme) NPM modules
- [Docker Desktop](https://www.docker.com/products/docker-desktop) available for Mac, Windows, and Linux

```
$ npm install got socks-proxy-agent cross-spawn --save
```

```js
const got = require("got");
const spawn = require("cross-spawn");
const { SocksProxyAgent } = require("socks-proxy-agent");

// Launch a TOR proxy via Docker
// @see https://github.com/osminogin/docker-tor-simple
const proxy = spawn("docker", [
  ...["run", "--rm", "-i", "-a", "stdout"],
  ...["-p", "127.0.0.1:9050:9050/tcp"],
  ...["osminogin/tor-simple:latest"],
]);

// Wait until the socks5 proxy server is up and running
proxy.stdout.on("data", (data) => {
  process.stderr.write(data);
  if (data.toString().includes("Opened Socks listener")) {
    run().finally(() => proxy.kill("SIGINT"));
  }
});

// Configure an HTTP client using socks5 proxy
const client = got.extend({
  agent: {
    https: new SocksProxyAgent("socks5://localhost:9050"),
  },
});

// TODO: Write some code that requires a proxy
async function run() {
  const body = await client.get("https://jsonip.com/").json();
  console.log("Client IP:", body.ip);
}
```

#### Links

  - [GOT through SOCKS5 proxy (TOR)](https://github.com/sindresorhus/got/discussions/1785)
What Inspired You To Learn To Code?
Tags: watercooler, reflections
Published: 2021-03-11 16:10:32

I hacked together something special to me yesterday. I've been keeping it running in the background and found that It's extremely relaxing. 

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">A week off work with nothing to do. So I made a thing.<br><br>🎶 Musical OSM Edits...<a href="https://t.co/07ZeNrjYWf">https://t.co/07ZeNrjYWf</a><br><br>🔊 Sound on and relax... <a href="https://t.co/2pA8AIslNP">pic.twitter.com/2pA8AIslNP</a></p>&mdash; 𝘈𝘭𝘦𝘹 𝘊𝘩𝘪𝘶☁ (@chiubaca) <a href="https://twitter.com/chiubaca/status/1369683919176622080?ref_src=twsrc%5Etfw">March 10, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

It's special because it was directly inspired by a CodePen I saw a few years ago called [Trams of Helsinki](https://codepen.io/teropa/pen/mBbPEe). I promised myself that I would create something similar once I learnt how to code.

Coming from a background in GIS (Geographical Information Systems) I've always been drawn to map oriented data visualisations. You can get pretty far with desktop applications such as [QGIS](https://www.qgis.org/en/site/) and [ArcMap](https://desktop.arcgis.com/en/arcmap/). But I was always impressed with those who could create these data visualisations using code. 

2017 was when I decided I was going to transition my career from a GIS consultant to web-developer. During this time I self-taught myself with texts books, Free Code Camp and lots of YouTube! 

Somewhere along this journey, I forgot about what originally inspired me to start this journey in the first place. It was to create **Whimsy and interesting data visualisations**! 

It kind of felt like I brought my coding journey full circle by creating this. It's interesting and constructive to look back on how far you've come sometimes.

---

Tell me about what inspired you to start your coding journey!
CSS variable chapter two "how to override CSS variable" 🤹‍♂️
Tags: css, tutorial, todayilearned, codepen
Published: 2021-03-11 16:06:56

Hello dear folks 😉

In the last [CSS variable chapter](https://dev.to/atulcodex/css-variable-first-chapter-3gj9) we have learned about how to create CSS variables and use them.

{% link https://dev.to/atulcodex/css-variable-first-chapter-3gj9 %}

In this post, we'll learn about "how to overriding variables"

In some cases, we need to make changes in CSS variable values at a certain level of our project, that's why we use this override feature.

Now imagine that we want to change our item card's headline and button color, so we'll use this code in our **item** selector.

```
.item {
    --red-color: green;
    background: var(--project-card-bg);
}
```

To clear your confusion look at this codepen project 👇

{% codepen https://codepen.io/atulcodex/pen/abBRBqm %}


hmmm, that's it for this DEV post and in the next post, we will learn about the "Local CSS variable".

If you have any questions about CSS override you can comment below, i will reply asap ;)
How to detect and update to the latest version with Nuxt PWA
Tags: tutorial, vue, nuxt, pwa
Published: 2021-03-11 16:05:56

<!--
Title: Detect and update to the latest version with Nuxt PWA
Tags: tutorial, vue, nuxt, blog
-->

# Introduction

I was working on one of my Nuxt projects and noticed that some users were using old versions, which was causing some errors to pop up.

I investigated and learned that sometimes PWAs don't update if the user doesn't manually refresh the website. So...

**Let's learn how to automatically update to the latest PWA version.**

---

## Before we start

This is a simple tutorial for projects with Nuxt and the PWA module, nothing else is required.

### Requirements

- Nuxt
- Nuxt PWA module

---

## Create a new plugin

To start, you will need to go to your plugins directory and create a new JavaScript file. I will name it `pwa-update.js` but feel free to use whatever you want to.

```js
// pwa-update.js

export default async (context) => {
  const workbox = await window.$workbox;

  if (!workbox) {
    console.debug("Workbox couldn't be loaded.");
    return;
  }

  workbox.addEventListener('installed', (event) => {
    if (!event.isUpdate) {
      console.debug('The PWA is on the latest version.');
      return;
    }

    console.debug('There is an update for the PWA, reloading...');
    window.location.reload();
  });
};
```

---

## Add the plugin to the Nuxt config

Then we have to add it to the plugins array on `nuxt.config.js`.

```js
// nuxt.config.js

// ...

  plugins: [
    { src: '~/plugins/pwa-update.js', mode: 'client' },
  ],

// ...
```

---

## End

And that was it. Easy right?

<!-- INCLUDE -->

### Self-promotion

If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰

- [GitHub](https://redirect.akbal.dev/github)
- [Twitter](https://redirect.akbal.dev/twitter)
- [Dev.to](https://redirect.akbal.dev/dev.to)
- [Medium](https://redirect.akbal.dev/medium)
- [LinkedIn](https://redirect.akbal.dev/linkedin)

Or support me financially. 💸

- [GitHub Sponsors](https://redirect.akbal.dev/github/sponsor)
- [LiberaPay](https://redirect.akbal.dev/liberapay)
- [PayPal](https://redirect.akbal.dev/paypal)

<!-- /INCLUDE -->

### Conclusion

Congratulations, today you have set up automatic PWA updates for your project.

**Let me know if this tutorial was useful to you in the comments!**
Back to coding with Our Time For Tech
Tags: beginners, womenintech, firstpost, devjournal
Published: 2021-03-11 16:04:52

My journey in Tech started almost 10 years ago when I got my first web developer position at a digital agency. After a few years working I decided to take a small break, and that small break turned into almost 4 years as a stay-at-home mom.

I always knew sooner or later I would come back so, when I felt it was the right moment to start job-hunting, for a couple of months I used every free minute I had to go over as many freeCodeCamp courses I could and to read as many articles I found and was when I realised I remembered more than I thought.

But I think knowing how to code is not enough anymore. Nowadays it is much more difficult to find a dev position than it was 10 years ago, when it could be done by knowing some HTML, CSS, Javascript or a CMS like WordPress. Also now I'm looking for a more specific role, it needs to be remote, preferably within a team... That's why when I discovered [Our Time For Tech] (https://ourtimefortech.org/) (A nonprofit online program that empowers early-career & career-changing Women in Tech) and its codeCollab program I knew it was the final push I needed.

I've been lucky enough to be part of it and I would like to share my journey with you. Over the next 12 weeks we (a group of 5 female coders) with the help of two experienced developers will be building a web app where we not only will develop further our coding skills, but also will learn and develop important ones, like team collaboration and communication, among others.

## So, what have I done so far? ##
As a brief recap, things I (we) have been working on over the last two weeks:
* Setting up the environment. Installing Rails 6, Node, Yarn and Postgresql. Dealing with errors during the installation, like the need of a different Ruby version.
* Learning how to make a pull request. During my previous experience as a developer I never had to used them, and even if I had a good knowledge of git I had forgotten most of it. Also I think back at that time pull requests weren't so widely spread in work environments as they are now, but I can be mistaken on this affirmation.
* Reading a lot about Ruby on Rails as I have never used it before, migrations, SQL commands, CLI commands... Searching and going through technical documentation when I get stuck.

And last, but not least:
* Thinking big: we are not only supposed to implement the tasks we are told, we are in charge of deciding (or trying at least) the best way of doing things, what can and cannot to deliver (find the MVP), collaborating and thinking as a group. (With the proper guidance of course). 

This last point was probably the one I was more worried about at the beginning, but now is probably the one that motivates me more. Looking forward to another week of challenges!
Hybrid AWD/RWD with Bootstrap
Tags: bootstrap, css, scaling, breaking
Published: 2021-03-11 16:01:27

I'm new to Bootstrap, but with a few years of dated frontend experience, so please bear with me a little.

How do I approach (using Bootstrap) delivering identical look & feel, scaling on displays 1440 wide and up, but when going down, from that resolution, revert to breaking as screen goes smaller?

I would prefer to avoid using pixels altogether as they don't describe display size, but are a function of both size and pixel density.  Or talk me out of it if I am making wrong assumptions.  It's just that my Samsung Galaxy Note 4 unit has the resolution abilities higher than my laptop monitor, but I don't want to deliver such tiny items to the mobile users.

Thank you.
Clean Contact Us Form In Bootstrap 5
Tags: css, beginners, webdev, uiweekly
Published: 2021-03-11 15:40:09

We previously made a different type of Contact us form in pure CSS and HTML. So here we made a clean and simple Contact Us Form In Bootstrap 5 with the help of CSS properties.

In this element we modify bootstrap classes with is used input fields and buttons classes. Also, we used custom classes to make this attractive contact us form. We used custom background color and also used hover and effects in the input side buttons side. This is a fully responsive contact us form for mobile and tablet.

Make it yours now by using it, downloading it, and please share it. we will design more elements for you.

[Source Code](https://w3hubs.com/clean-contact-us-form-in-bootstrap-5/)
Office Lunch Delivery app - part 1
Tags: nuxt, nestjs, mongodb, vuetify
Published: 2021-03-11 15:33:57

Hello folks! This is my first post here.
Today I started developing **Your Kitchen** &mdash; a simple lunch delivery service for one restaurant in my hometown. This series of blog posts will be my logbook. Hope my experience will be useful to someone as well. Let's go!

Let's create Nuxt App and choose **Universal**, **axios**, **PWA** and **Vuetify** in options
```bash
yarn create nuxt-app your-kitchen
```

I highly recommend to use SCSS and Pug preprocessors:heart:
```bash
yarn add -D pug pug-plain-loader
yarn add -D sass sass-loader@10 fibers
```
In VS Code install these extensions:
- [Vetur](https://marketplace.visualstudio.com/items?itemName=octref.vetur)
- [Bracket Pair Colorizer](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer)
- [Trailing Spaces](https://marketplace.visualstudio.com/items?itemName=shardulm94.trailing-spaces)
 
That's it. Now we're ready to start. The next part comes soon...
Using Camunda with .NET
Published: 2021-03-11 15:19:56

This is a tutorial how to interacte with Camunda BPM within a .NET Core application. [Camunda BPM](https://docs.camunda.org/manual/latest/) is an open source workflow engine written in Java. The engine offers a Java-API, but also a very good documentated REST-API. You can implement your own REST-Client or generate it from the provided OpenApi description. The [Camunda.OpenApi.Client Nuget package](https://www.nuget.org/packages/Camunda.OpenApi.Client/) includes a pre-buildet generated Camunda REST-Client from the OpenApi description. You don't have to take care about the generatation of the REST-Client, you can just use it.  You can have a look at the [Github Repo](https://github.com/silvanbrenner/camunda-csharp-client/tree/main/camunda-csharp-client-generator) to see how the generatation of the REST-Client works.

You can add the Nuget Package to your project:
```
Install-Package Camunda.OpenApi.Client -Version 1.0.1

```

After that you can define your own extension to add this later over Dependency-Injection:
```csharp
public static class CamundaClientExtension
    {
        public static void AddCamundaClient(this IServiceCollection services)
        {
            var config = new Configuration
            {
                BasePath = "http://localhost:8080/engine-rest",
                UserAgent = "CamundaClient"
            };

            // add all needed api's
            services.AddSingleton(new TaskApi(config));
            services.AddSingleton(new TaskVariableApi(config));
            services.AddSingleton(new ProcessInstanceApi(config));
            services.AddSingleton(new ProcessDefinitionApi(config));
            services.AddSingleton(new DeploymentApi(config));
            services.AddSingleton(new MessageApi(config));
            services.AddSingleton(new HistoricProcessInstanceApi(config));
            services.AddSingleton(new HistoricActivityInstanceApi(config));
        }
    }
```

Add `services.AddCamundaClient();` in Startup.cs on the `ConfigureServices` method:
```csharp
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddCamundaClient();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo {Title = "TestWebApp", Version = "v1"});
    });
}

```

Now you can inject the api services everywhere in your application. For example in a ApiController:
```csharp
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
    private readonly TaskApi _taskApi;

    public ExampleController(TaskApi taskApi)
    {
        _taskApi = taskApi;
    }

    [HttpGet]
    public IEnumerable<TaskDto> Get()
    {
        return _taskApi.QueryTasks();
    }
}
```
Writing pre-request scripts in postman 
Tags: postman, devops, writing, beginners
Published: 2021-03-11 15:18:43

A pre-request script (PRS) is basically a function or code logic that runs before a server request. You may be thinking to yourself "where and when would I ever need this?🤨"
Let's say you were working on a server that has endpoints which require the attachment of jwt tokens to each endpoint. It will be counter-productive to manually use the sign-in/login endpoint to always retrieve the token after login and then assign it to the headers of the endpoints you want to use. This gets even more tedious when the token expires in a very short time.
So to increase productivity in a situation like this, pre-request scripts help to run the sign-in/login endpoint while setting the token and other environmental variables we need to run our request.
PRSs are written in the "pre-req." tab for whichever request you want to run and they are written in javascript. Once code is put under the "pre-req." tab, there should be a green glow beside the tab indicator as shown below. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c25sjxsnc4dh24gg4kar.png)
PRSs can also be assigned to entire postman collections or folders to allow them run before every request in the collection/ folder. This can be done by clicking on the ellipses beside the collection and then clicking the edit tab.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1nmzemho8lca1n72s2se.png)
In a PRS, postman has made a `pm` object available that contains various properties and methods. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zuo18l712pvfv2cxyyms.png)
An example to fit the use case I presented earlier can be seen below
```
const devOnline = <your serverlink>
const username = "joojodontoh@gmail.com"
const passwordStg = "*****"

pm.sendRequest({
    url: devOnline + '/user/signin',
    method: 'POST',
    header: {
        "Client-key": pm.globals.get('Client-key'),
        "Content-Type": "application/json"
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            email_phone: username,
            password: passwordStg
        })
    }
}, function (err, response) {
    if (err) {
        return console.error(err)
    }


    const { code, message, data } = response.json()
    console.log('data:', data)


    pm.globals.set('UID_STG', data.uid)
    pm.globals.set('U4T_STG', data.token)
})
```
The `pm` object can be used to set and get environmental/global variables; `pm.globals.set('UID_STG', data.uid)` & `pm.globals.get('UID_STG')`. It can also be used to send requests with its `sendRequest` method.
Just like writing code anywhere else, there are times when you'll need to debug the PRS for errors via a console. Holding down (CMD/CTRL + ALT + C) will automatically open the postman console for you. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ofr3m5vywlwsfkut19n.png)
Try writing a pre request script and share your experience with it.