teleren/devto huggingface dataset:
Vue and Input File - Clear File or Select same file
Tags: vue, webdev, javascript, input
Published: 2023-06-21 20:28:58

Have you ever had the case where ou have a file selector component, you clear the file model but then you can't select the same file again?
![File selection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/teencvkudzxowih3kwt4.gif)
Codepen: https://codepen.io/schirrel/pen/YzRGrvq

Well its kinda hard and curious to explain.
First of all to the TL/DR:
You need to use Vue's `$refs` and set the input to null.

Now if you want to understand why, let's pass thru some important stuff:

First: Vue doesn't work with v-model and file input, even has a discussion about it on the offical Vue's repo: [Discussion](https://github.com/vuejs/Discussion/issues/24).

Now lets undestand why doesnt work, two main things:

1. input with `type="file"` only triggers `change` event, while v-model listen to `input` event.
2. `v-model` needs to set the `value` html attribute, if you ever try to do `:value="myFileModel"` this error will show up:

> Error in nextTick: "InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.


So with this comes a question: _**how to a clear a file, and most important, how make it possible to select again?**_

Lets paint a simple use case: You have your own file wrapper the uses a file input (obviously) but you save the file on the `data`. Example:
```vue
<template>
 <label for="inputFile">
      Click here to select you file
      <input type="file" name="inputFile" id="inputFile" @change="selectFile" />
    </label>
    <span v-if="file">
      File Selected {{ file.name }}
      <button @click="clearFile">remove</button>
    </span>
</template>
<script>
export default {
  data() {
    return {
      file: null
    };
  },
  methods: {
    selectFile(event) {
      this.file = event.target.files[0];
    },
    clearFile() {
      this.file = null;
    }
  }
};
</script>
```
Even if `clearFile` is setting `file` as null, when selecting the file again the @change wont be triggered again. Thats why because the html value attribute still the same, the `file` prop on data doesn't affect it. Take a look at the [codepen](https://codepen.io/schirrel/pen/YzRGrvq) example.

Once we have seen that `:value` don't work with files, the proper way to do this is acessing the HTML `<input type="file" />` and reset this value programmatically.

By adding a `ref="fileInput"` to the `<input>` and inside the `clearFile` method add:
```js
this.$refs.fileInput.value = null
```
Now it works:

![Vue select same file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cgtgl203bd58gak1gk9.gif)

The codepen final solution: https://codepen.io/schirrel/pen/XWyjeOw

Note: this is common behavior across frameworks;
Why it's always worth to optimize website performance
Tags: webperf, frontend, javascript, webdev
Published: 2023-06-21 20:26:12

On one of [meet.js Katowice (Poland)](https://crossweb.pl/en/event-series/meet-js/) we had an interesting conversation about performance. 

One of the participants asked: 
**"Should we always optimize the web performance of our websites?"**

He stands for: not always, it depends on your target audience, their internet connection, and the devices that they use.
If you are sure that your Customers/Visitors are eg. IT guys that always will go to your website from MacBook Pro with an extra super-fast fiber optic internet connection, you don't need to.

As I can partially agree with this, there is always but :) 

Let's start with, why I can agree.


![Agree GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xroqevdq34wroahaw741.gif)

Optimizing web performance (especially [js long task](https://web.dev/optimize-long-tasks/), [TTFB](https://web.dev/ttfb/), [FID](https://web.dev/fid/), [INP](https://web.dev/inp/)) can be tricky, that means it's also expensive, often you need to dig very deep into your application, exchange some libraries, rewrite functions, or even change framework you use. 

Sometimes business could not agree on spending time, resources, and money on optimizing things that will not bring profits (we are considering the situation from the example above, our target audience use fast internet + high-end devices and for this target, our website is loading super fast).

But ...

![But GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vpsqu1he06oz0komflj5.gif)


Even in this case, we should care about stuff that is relatively easy to optimize, eg. don't load big images/movies or don't fetch unnecessary data (if you need 2 items from API and inside you need only 2 properties, don't fetch 100 items with all 300 properties that you will never use).

Why?
1. Cost optimization
As a company we are always happy when we can save some money, making our resources smaller will help us reduce the cost of storage. Also when we are using SSR (Server Side Rendering) js long tasks and memory leaks can lead to high memory and CPU consumption on the node server that is responsible for rendering our website and this also can generate high costs (especially if need to deal with a lot of traffic). 

2. Ecology
Every KB of data sent over the internet, each ms of CPU time, hosting all those not optimized images, etc., all this uses energy and affects the climate of our planet.
You can check your website carbon footprint on WebPageTest website, more info can be found on their [blog](https://blog.webpagetest.org/posts/carbon-control/)
![Web Page Test Carbon Control](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hv5wh4unroglfusf1ajx.png) or on [https://www.websitecarbon.com/](https://www.websitecarbon.com/)

3. Good practices 
It's always good to do things "in the right way", if you will learn web performance good practices, in your next project (or company) this could be a key to success. 

Let me know in the comments what is your opinion on this subject, always optimize, or maybe not?
Small sum types in Golang
Published: 2023-06-21 20:13:13

You can model sum types in golang as following

```golang
import "github.com/samber/mo"

// tags and their types
type (
	Id    int
	Phone string
	Email string
)

// UserKey is a sum type
type UserKey = mo.Either3[Id, Email, Phone]
```

I find this implementation to be quite minimal and less clumsy than [alternatives](https://github.com/BurntSushi/go-sumtype). Sure, you don't get nice exhaustive pattern matching. Also, type inference gets in the way when instantiating `UserKey` (though you can wrap it in constructor functions). But expressing your intent using types still makes your code much more convenient and easier to understand.
Why am I posting to Dev now? Hackathon!
Tags: hackathon, softwareengineering, javascript, python
Published: 2023-06-21 19:54:29

## Launch in ...3...2...1...

I recently received an email about the [1Password Hackathon](https://hashnode.com/hackathons/1password). I haven't entered a hackathon for a bit, so I figured this is a good time and it provided the impetus to start writing about modern software development! And also...it's one of the requirements to enter the hackathon. 😅

As a modern software developer, authentication is extremely important and vital to any production application. If you're building an application on your laptop or desktop, usually you do not have to log into it. That's the bane and bliss of most tutorials, they show you how to build an application, though deploying the application is actually what can initially take the most time and effort. Of course, a single tutorial would not cover all of the steps otherwise you would get overloaded! 🤯

There are several steps to building and deploying production applications - version control, handling merge conflicts among dev team(s), pull requests, code reviews, unit testing, integration testing, end-to-end testing, visual regression, automated pull request previews, staging environment(s), package management, security audits of application package dependencies, documentation, API design, proper handling of API keys, accessibility, cross-browser compatibility, CI/CD pipelines, user management, backend database(s), user authentication, user authorization, application load time performance metrics, application secrets management, 2FA/MFA and much more!

Hence, the inspiration for `Build It => Deploy 🚀` ...@builditdeploy.
 
So, I'll start with tracking my progress through the hackathon and other interesting articles along the way.  Also, I am using this opportunity to consider different writing platforms.

Here we go...happy coding, @builditdeploy! 🥳

---

Photo courtesy of <a href="https://unsplash.com/@spacex?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">SpaceX</a> on <a href="https://unsplash.com/photos/uj3hvdfQujI?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
React Collapsible Component with Auto Height Detection.
Tags: react, typescript, programming, frontend
Published: 2023-06-21 19:28:57

Collapsible components with variable heights are hard, but not anymore, this example will make you rethink how you develop this in your company library from now on! Let's get into it!

## Step 1: Create the Collapsible Component

For this example, I'm using styled-components but feel free to use plane css, or any css-in-js library you prefer

```jsx
// Collapsible component 

interface Animation {
  duration?: number;
  ease?: string;
}

interface CollapsibleProps {
  children: React.ReactNode;
  open: boolean;
  animation?: Animation;
}

const defaultAnimationValues = {
  duration: 0.2,
  ease: "ease-in-out"
};

const CollapsibleWrapper = styled.div<{ open: boolean; animation: Animation }>`
  display: grid;
  grid-template-rows: ${(props) => (props.open ? "1fr" : "0fr")};
  opacity: 0;
  transition: all ${(props) => props.animation.duration}s
    ${(props) => props.animation.ease};
  opacity: ${(props) => (props.open ? 1 : 0)};
`;

const CollapsibleInner = styled.div`
  overflow: hidden;
`;

export const Collapsible: React.FC<CollapsibleProps> = ({
  children,
  open,
  animation = defaultAnimationValues
}) => {
  return (
    <CollapsibleWrapper open={open} animation={animation}>
      <CollapsibleInner>{children}</CollapsibleInner>
    </CollapsibleWrapper>
  );
};
```

I added extra props to control animation timing and speed to make more customisable, beyond that there's not to much here here except for one detail...

```tsx
grid-template-rows: ${(props) => (props.open ? "1fr" : "0fr")};
```

This is the secret sauce! This line will actually open and close the Collapsible component adjusting the wrapper component height based on the children height!

## Step2: Using the component

This is also incredible straightforward, set the state for toggling "show" and render whatever you want inside your new Collapsible component!

```tsx
// App component 

export default function App() {
  const [show, setShow] = React.useState(false);
  return (
    <div className="App">
      <button onClick={() => setShow(!show)}>click</button>
      <Collapsible open={show}>
        <div className="bg-gray-100 py-4">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      </Collapsible>
    </div>
  );
}
```

![Magic gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3jsvm55p9mqzngtlsb0.gif)

Now you can stop using those crazy height-controlled components! Wrap the code from the next codesanbox

{% codesandbox https://codesandbox.io/embed/collapsible-y2x7ps?fontsize=14&hidenavigation=1&theme=dark %}
My 150-Day Full-Stack Web Development Challenge: Day 1
Published: 2023-06-21 19:52:45

Introduction:
Hello there, fellow tech enthusiasts! I am Pranav, an 18-year-old B.Tech student embarking on an extraordinary journey towards becoming a full-stack developer. Today marks the beginning of my 150-day challenge, where I'll immerse myself in the world of web development, honing my skills and exploring the vast possibilities of this dynamic field. Join me as I share my triumphs, tribulations, and everything in between.

Day 1: Reviving HTML and CSS, Building an Amazon Clone
As the sun rose on this exciting endeavor, I found myself eagerly dusting off my HTML and CSS skills. These foundational languages are the building blocks of the web, and it felt invigorating to reconnect with their syntax and structure. With a renewed sense of purpose, I set out to create my very own Amazon clone.

With every line of code, I felt a surge of anticipation and creative energy. The process of recreating such a widely recognized e-commerce platform was both thrilling and challenging. From crafting the layout and user interface to perfecting the intricate details, every step brought me closer to realizing my vision.

As I delved deeper into the project, I encountered moments of frustration and doubt. But I reminded myself that growth often emerges from facing challenges head-on. With determination as my guide, I sought solutions, referring to documentation, seeking guidance from online communities, and experimenting with different approaches. Each hurdle I overcame provided invaluable lessons and bolstered my confidence.

Throughout the day, I witnessed my Amazon clone taking shape, slowly but surely. It was awe-inspiring to witness the transformation of a blank canvas into a visually appealing and functional website. The feeling of accomplishment washed over me, igniting a fire within to continue this incredible journey.

Closing Thoughts:
Day 1 of my 365-day full-stack web development challenge was a captivating experience, fueling my passion for coding and igniting my ambition to master every facet of this dynamic domain. Brushing up my HTML and CSS skills while building an Amazon clone reminded me of the boundless possibilities that lie ahead.

As I prepare for the next phase of my journey, I am brimming with excitement and curiosity. The road may be long, filled with ups and downs, but I am determined to persist, learn, and grow. Join me as I continue to document my progress, sharing insights, discoveries, and, undoubtedly, a few humorous anecdotes along the way.

Stay tuned for the next chapter of my adventure, where I dive deeper into the realm of web development, unraveling the secrets of JavaScript and beyond. Until then, fellow coders, keep coding and dreaming big!

Signing off,
Pranav
Why does it a long time launch a product?
Published: 2023-06-21 19:28:18


Usually it will take less than half the time it takes to develop a software but because inclusivity for all (possibly), it takes twice or thrice that. We try to account for all possible scenarios.
  
 [A list of biggest GDPR compliance fines for 2022](https://www.eqs.com/compliance-blog/biggest-gdpr-fines/)

We can't take humans out of the equation; we build for humans and with humans. This inclusivity for all is major reasons for most cyberattacks as the additional "features" makes a relatively simpler system more complex and introduces vulnerabilities that are sometimes difficult to mitigate without breaking a whole system. The extremes are government regulations, policies and religions beliefs and political correctness.

Over a decade in my software development journey. One of the things I have noticed is that we developers think we are building for ourselves without considering the average user (the actual user) of the platform. This slows development such that an MVP that will take a month or two to build might take several months and sometimes end up in the 12+ months mark. Software development is an iterative process; We can't consider all possible scenarios in the same vein we can't leave some essential things out.
Does that mean we should ask users what they want all the time? No!!! As Phil Libin ( creator of evernote and four other startups) puts it: " build for yourself; it is better for 100 people to like your product than a million people who kinda like it." The" build it for yourself" doesn't mean for your usage but how you as a regular user would prefer it because if it is left to us developers/engineers everything should be terminal base, sorry Windows users😌. 

Software Development is an iterative process; start with the knowns to get to the unknowns just like everything in life. You can't please everyone. Launch the product, the world has been waiting too long for it.

Launch The Product!!
Create a Nuxt Bridge App
Tags: webdev, vue, nuxt
Published: 2023-06-21 19:26:24

Even tho the Nuxt docs is pretty good, i hadn't found a single tutorial on creating a nuxt bridge app, so why not create right? Docs is good, but sometimes is need a more straight forward thing!

## Step 1 - Create a Nuxt 2 App

```sh
yarn create nuxt-app nuxt-bridge-app`
```

You can select the config of your app as you like, mine was:

![Nuxt CLI Setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imo3rm8pnycfrqq40quv.png)



After install we can run execute yarn dev and see the app running

![New app running on localhost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5qlmn4mv04y9uz3ump4.png)


## Step 2 - Upgrade to latest Nuxt 2
As stated at the migration docs we need to use the latest Nuxt 2 release, so far today (16/03/2023) the version is 2.16.2.
We replace the version on package.json and once again execute yarn install, now our main dependencies are:

- "nuxt": "2.16.2",
- "vue": "2.7.10",

## Step 3 - Install Nuxt Bridge
The docs says to install as

```sh
yarn add --dev @nuxt/bridge@npm:@nuxt/bridge-edge

```
## Step 4 - Update scripts at package.json
Now we are going to use nuxi instead of nuxt to run and build the app.
At your package.json replace the content at the script's prop to:

```json
"scripts": {
   "dev": "nuxi dev",
   "build": "nuxi build",
   "start": "nuxi preview"
  }

```
## Step 5 - Update Nuxt config
Now update the nuxt.config file to use Nuxt Bridge, import `defineNuxtConfig` from '@nuxt/bridge' and wrap it arount the config object:

```js
import { defineNuxtConfig } from '@nuxt/bridge'

export default defineNuxtConfig({
  // Your existing configuration
})

```

If you are using typescript you need to add the below line at your tsconfig:

```json
 "extends": "./.nuxt/tsconfig.json"

```
And disable typescript from bridge at nuxt.config file to avoid conflict between the Ts on bridge and on your configuration:

```js
bridge: {
    typescript: false
  },

```
Now you can simply run again yarn dev and now you are using Nuxt Bridge on you project

![Running nuxt app with Bridge](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhc4c0nr4850atui05ge.png)


The source code is on https://github.com/schirrel/nuxt-bridge-app
TERMINAL COMMAND LINE ORDERS
Tags: terminal, ubuntu, shell, bash
Published: 2023-06-21 19:19:19

 ✨Let's explore some background on the terminal🏃‍♂️🏃‍♂️🏃‍♂️....
**What is the terminal?**
Terminal is an application that lets you interact with your computer.You usually give instructions to your computer through clicking around in applications or typing keys to make
things happen.
Terminal lets you do many of the same things; it’s just
more direct. You can give clear, structured orders to your computer using the terminal.
You just have to be patient and willing to try them!
**"Where am I?" in my computer**
When you first launch Terminal, you'll likely have an empty window with not much going on. My Terminal window looks like this, but yours is probably a different color or set of text on the left (which is fine!)
I see a simple dollar sign and a blinking cursor, but you might see the name of your computer too or other symbols:
💁💁💁..
**Run this command **

```
pwd
```
**Finding destinations**

In your computer, you can go pretty much anywhere you want. First, though, you must know the destinations available to you.
On the command line, type the following command (ls , which is short for list), and press the Enter key on your keyboard.
**Run this command **

```
ls
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/44r7kp2iyhmsmu92y3wm.png)

**Going to destinations**

Now that you've revealed possible directories (folders) available to you, you can move around them using a different command:cd which is short for "change directory," plus the name of the folder where you want to move.
For example, let's say I want to change locations in my system and move into the "Music" folder. This was listed as one of the options in the output from our ls command. I'd type:

```
    cd Music
```

Here's what my Terminal looks like after running cd Music:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s24w2rmfa7mpojjgyyhu.png)

**Create directory**

It's now time to create a folder within your system.
Yes, you could just do this via Finder or whatever tool you use to browse and create files now. However, there are advantages to doing this via the terminal, especially if you want to get more into programming!
How does one go about creating a folder in Terminal? Time for a new command!
Use the command  mkdir  to create a directory.  mkdir  is short for "make directory." Specify the name of the directory (folder) you want to create just after it. If I wanted to create a folder called  new-folder , I would run:

```
    mkdir new-folder
```
**Move File**
 if you want to move file in the same path or another directory
```
mv fileName  /temp/fileName
```
**copy File**
 if you want to cope file in the same path or another directory
```
cp fileName  newfileName
```
**Remove File**
 if you want to remove file in the same path or another directory
```
rm fileName
```
**Remove folders**
 if you want to remove folders in the same path or another directory
```
rmdir folderName
```
Navigation Link - Swift UI iOS 16
Tags: swift, ios, xcode, swiftui
Published: 2023-06-21 19:01:02

Ever been using NavigationLink inside a NavigationView and got this deprecation warning in Xcode?

![Xcode deprecation warning - 'init(destination:isActive:label:)' was deprecated in iOS 16.0: use NavigationLink(value:label:) inside a NavigationStack or NavigationSplitView](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ukb1q3zpi9nx7z1gdylb.png)

Here's how to fix it!

##Before

Let's start with an iOS15 example of a `NavigationView` with a `.stack` NavigationViewStyle, and a NavigationLink which links to `SecondView` when the button is pressed. 

```swift
import SwiftUI

struct ContentView: View {
    @State var showSecondView: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                Button {
                    showSecondView.toggle()
                } label: {
                    Text("Show Second View")
                }
                NavigationLink(
                    destination: SecondView(),
                    isActive: $showSecondView
                ) {
                    EmptyView()
                }
            }
        }
        .navigationViewStyle(.stack)
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("Hello! I'm the second View")
        }
    }
}
```

##After

To update for iOS 16 and remove the deprecation warning we can:

- Change `NavigationView` to `NavigationStack`
- Change `NavigationLink` to `navigationDestination`
- Remove `.navigationViewStyle(.stack)`

```swift
struct ContentView: View {
    @State var showSecondView: Bool = false
    var body: some View {
        NavigationStack {
            VStack {
                Button {
                    showSecondView.toggle()
                } label: {
                    Text("Show Second View")
                }
                .navigationDestination(
                 isPresented: $showSecondView) {
                     SecondView()
                 }
            }
        }
    }
}

```

Hope that helps anyone else who has hit the same warning!