teleren/devto huggingface dataset:
The difference between created and mounted in Vue
Tags: vue, javascript, webdev, tutorial
Published: 2022-05-11 00:08:28

In a previous article, I covered all the [different lifecycle hooks in Vue](https://fjolt.com/article/vue-lifecycle-hooks). One of the things that most people get confused on when talking about lifecycle hooks, is the difference between `created` and `mounted`. They both have similar names, and they feel like they should do the same thing, but there are some subtle differences.

## The Difference between created and mounted in Vue
To begin with, both `created()` and `mounted()` have access to the data and props on your prototype. For example, both hooks will console log 'My Message' below, as well as the default value for `myProp`, which is 'Some Prop':

```javascript
export default {
    data() {
        return {
	        msg: 'My Message'
        }
    },
    props: {
        myProp: {
            type: String,
            default: 'My Prop'
        }
    },
    created() {
        console.log(this.msg);
        console.log(this.myProp);
    },
    mounted() {
        console.log(this.msg);        
        console.log(this.myProp);
    }
}
```

### Prop Inheritance for created and mounted]
Note: even if you set a property, it will still be available both in `created()` and `mounted()`

**The fundamental difference** between `created()` and `mounted()` is you do not have access to the DOM in `created()` yet. In our example, if we try to reference `this.$el`, it will return `null` in `created()`, and it will return the DOM element in `mounted()`:

```javascript
export default {
    created() {
        // Returns null
        console.log(this.$el);
    },
    mounted() {
        // Returns the DOM element in console:
        console.log(this.$el);     
    }
}
```

As such, any DOM manipulation, or even getting the DOM structure using methods like `querySelector` will not be available in `created()`. As mentioned in the article on [lifecycle hooks](https://fjolt.com/article/vue-lifecycle-hooks), `created()` is great for calling APIs, while `mounted()` is great for doing anything after the DOM elements have completely loaded.

## Composition API and created or mounted
The one caveat to this is that if you are using the Composition API, `created()`, and indeed `beforeCreated()` no longer exists. You have to instead use `setup()`. This function takes the place of both `created()` and `beforeCreated()`. Therefore, the DOM is still not available in `setup()`. In the Composition API, `mounted()` remains unchanged.
How to give Props Default Values in Vue
Tags: vue, javascript, webdev, typescript
Published: 2022-05-11 00:06:59

When we use components in [Vue](https://fjolt.com/category/vue), we often use [properties or props](https://fjolt.com/article/vue-how-do-props-work) to pass custom pieces of data down to the child component. For example, we can tell our child component that for this version of the component, "name" is set to "my-component":
```html
<Component name="my-component" />
```

If we try to call this component without a `name` prop, it returns `undefined` in the code, or just as no text when rendered in HTML. Let's say our `Component` looks like this:
```html
<script>
export default {
    props: {
        name: String
    },
    mounted() {
        console.log(this.name);
    }
}
</script>

<template>
    <p>
        Hi {{ name }}
    </p>
</template>
```

All our component does is defines a prop called `name` of type `String`, and console logs this property. It also displays it in the form `Hi {{ name }}`. The only issue here is that if `name` is undefined when the component is called, no default name is given. 

## Setting Default Prop Values in Vue
Setting defaults prop values in Vue is easy. If you are using the [Options API](https://fjolt.com/article/vue-composition-api-vs-options-api), then it's as easy as extending our property into an object. For example, if we want our `name` to have a default value of "**there**", then we update our prop to look like this:
```javascript
export default {
    props: {
        name: {
            type: String,
            default: "there"
        }
    },
    mounted() {
        console.log(this.name);
    }
}
```

Now if no name is given, the message will simply say '**Hi there**'

## Setting Default Prop Values in Composition API
In the composition API, defining props uses the `defineProps` function. This function follows the same syntax as props defined on the Options API. Defining a prop without a default looks like this:
```javascript
import { defineProps } from 'vue';
  
const props = defineProps({
    name: String
});
```

**And then to add a default value**, we extend `name` to have a default property, just as before:
```javascript
import { defineProps } from 'vue';
  
const props = defineProps({
    name: {
        type: String,
        default: "there"
    }
});
```

## Setting a Prop as required in Vue
To avoid the need for setting a default value on a property, we can force a property to be required by using the `required` field. For example, if we want our `name` property to be defined, we'd simply set `required` to `true`:
```html
&lt;script setup>
import { defineProps } from 'vue';
  
const props = defineProps({
    name: {
        type: String,
        required: true
    }
});
</script>
```
How to pass arguments to events like on:click in Svelte
Tags: svelte, javascript, webdev, typescript
Published: 2022-05-11 00:06:04

[Svelte events](https://fjolt.com/article/svelte-how-events-work) are the way we add interactivity to components in Svelte. A common issue with Svelte events is adding **arguments** to functions called within them. For example, suppose we have a basic counter, which increases any time the user clicks on it:

```html
<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
    const addToCounter = function() {
        ++x;
    }
</script>

<button id="counter" on:click={addToCounter}>{x}</button>
```

This works fine, but let's say we want to change it so that we increase the counter by a certain amount whenever it is clicked. We might try changing the code to something like this:
```html
<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
    const addToCounter = function(amount) {
        x += amount;
    }
</script>

<button id="counter" on:click={addToCounter(5)}>{x}</button>
```

**But this WONT work** - instead we need to change our event to contain a function instead. To add arguments to our `addToCounter` function, we have to do something like this instead:

```html
<button id="counter" on:click={() => addToCounter(5)}>{x}</button>
```

Here, we call a function, which returns the value produced by `addToCounter`. This also works for events, so if you want to pass the event or `e` object to your function, you could do something like this:
```html
<button id="counter" on:click={(e) => addToCounter(e)}>{x}</button>
```
How the TypeScript ReturnType Type works
Tags: typescript, javascript, webdev, tutorial
Published: 2022-05-11 00:03:50

The `ReturnType` in TypeScript is a utility type which is quite similar to the [Parameters Type](https://fjolt.com/article/typescript-parameters-utility-type). It let's you take the return output of a function, and construct a type based off it.

## The ReturnType Utility Type

The `ReturnType` utility type is very useful in situations where the output of a specific function needs to be taken in by another function. In that scenario, you might create a new, custom type, that the output of a function constrains itself to.

Let's look at a silly example to put it into context. Below, we define a new type, which has two properties, `a`, and `b`, both of which are numbers. A function then turns all numbers on this object into strings, and returns a new type. We define a custom type, called `Data`, which expects `a` and `b` to be strings.

```typescript
function sendData(a: number, b: number) {
    return {
        a: `${a}`,
        b: `${b}`
    }
}

type Data = {
    a: string,
    b: string
}

function consoleData(data:Data) {
    console.log(JSON.stringify(data));
}

let stringifyNumbers = sendData(1, 2);
consoleData(stringifyNumbers);
```

Since `consoleData` expects data to be of format `Data`, TypeScript throws an error if `a` or `b` are numbers. Our `sendData` function fixes that, by converting `a` and `b` to strings. 

The issue with this setup is if we added or changed `sendData`, or our input data, then `Data` would need to be updated too. That's not a big deal, but it's an easy source of bugs. As such, we can instead use `ReturnType` to simplify our type declaration. Our `Data` type can be written like so:
```typescript
function sendData(a: number, b: number) {
    return {
        a: `${a}`,
        b: `${b}`
    }
}
type Data = ReturnType<typeof sendData>
// The same as writing:
// type Data = {
//     a: string,
//     b: string
// }
```

Since `sendData` returns data in type `{ a: string, b: string }`, `Data` becomes that type. It means we don't have to maintain two copies of the output from `sendData` - instead we have one, inside the function, and a type that conforms to that, simplifying our code.
Day 32: no code :( but it's good :)
Published: 2022-05-11 00:01:42

Hi!
as promised yesterday today was the first day in a long time where I didn't write any line of code and I didn't do anything else expect working on the dissertation It had a happy ending though because I was able to finish writing and I just sent a draft, and you know what that means? I can now go to coding in a peaceful mind and that's what I plan to do tomorrow working on my task with my team and maybe take some rest to watch a movie I think I deserve it
now off to sleep

signing off...
How to make Git forget a tracked file now in .gitignore
Tags: git, codenewbie, tutorial, webdev
Published: 2022-05-11 00:00:44

When we track a file in git, it can sometimes get cached and remain tracked, even if we add it to our `.gitignore` file. This is simply because `.gitignore` prevents files from being added to Git's tracking system, but it will not actively remove those that are already tracked. This can lead to issues when you have something you no longer want to be tracked, but can't seem to remove it from your git repository.

Fortunately, there is an easy way to fix this. `git` has a built in `rm` function which lets us remove cached or tracked changes. To run it, you can use the following command to remove a specific file, where `[filename]` can be removed with the file you wish to stop tracking:
```
git rm --cached [filename]
```

Similarly, if an entire directory needs to be removed, use the `-r` flag which means **recursive**, to remove an entire directory and everything within it from tracking:
```
git rm -r --cached [directory]
```

After running this command, you can then add ammend your commit and push it to your remote:
```
git add .
git commit -m "Removed tracked files which shouldn't be tracked"
git push
```

**NOTE** this will not remove files from your local computer, but it will remove tracking of files from your git repository. It will also remove the files from other developers computers or servers upon your next `git pull`. Be careful with this command, as I accidentally deleted all images on [FJOLT](https://fjolt.com/) using it a couple of weeks ago. :)
Blog: Community Day returns on the 16th of May! 🎉
Tags: puppet, community
Published: 2022-05-11 16:59:22

---
title: Blog: Community Day returns on the 16th of May! 🎉
published: true
date: 2022-05-11 00:00:00 UTC
tags: puppet,community
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/posts/return-of-community-day/
---

We are excited to announce that community day is returning on May 16th 2022 and will be continuing every Monday for the foreseeable future.

## Why is community day so good anyway?

It means we get to spend time with our **amazing** community, understand how our content is being used and help level up our modules and tools by addressing issues and pull requests.

Community day benefits us as a team too!

- Promotes collaboration and healthy team work ❤️
- Upskills new _and_ existing engineers 👷🏾‍♀️
- Increases productivity 💯
- Overall increase of team morale 👍

## What to expect

We are here to help **you**!

- 🕘 We will be available between 9am and 5pm UK time
- 🏢 We hang out on [GitHub](https://puppetlabs.github.io/) and our [community slack channel](https://puppetcommunity.slack.com/archives/C11LCKKQ9)
- 📚 We want to help you with issues, pull requests and product related questions

## Signing off

That’s it for now! We are excited to see you all on Monday.

For more information about who we are and what we do in the Content and Tooling team, check out our intro [blog post](https://puppetlabs.github.io/content-and-tooling-team/blog/posts/team-rebrand/).
How to easily make every property in a type alias or interface to required properties in TypeScript?
Tags: typescript
Published: 2022-05-11 00:00:00

---
  title: How to easily make every property in a type alias or interface to required properties in TypeScript?
  published: true
  tags: TypeScript
  date: Wed May 11 2022 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/easily-make-every-property-type-or-interface-to-required-typescript
  cover_image: https://melvingeorge.me/_next/static/images/main-016593762712dfb7dfc286a4e5006d9b.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/easily-make-every-property-type-or-interface-to-required-typescript)
  
To easily make every property on a `type alias` or `interface` to required properties, you can use the `Required` utility type and pass the `type alias` or `interface` as the first type argument to it using the angled brackets symbol (`<>`).

### TL;DR

```ts
// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};

// make all the properties in the
// `Person` type to be required
type RequiredPerson = Required<Person>;

// contents of the `RequiredPerson` type
/*
{
  name: string;
  age: number;
}
*/
```

For example, let's say we have a type called `Person` with 2 optional properties called `name` having the type of `string` and `age` having the type of number like this,

```ts
// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};
```

Now to make all the properties in the `Person` type to be required we can use the `Required` utility type and pass the `Person` interface as the first type argument to it using the angled brackets symbol (`<>`).

It can be done like this,

```ts
// a simple type
// with optional properties
type Person = {
  name?: string;
  age?: number;
};

// make all the properties in the
// `Person` type to be required
type RequiredPerson = Required<Person>;

// contents of the `RequiredPerson` type
/*
{
  name: string;
  age: number;
}
*/
```

Now if you hover over the `RequiredPerson` type you can see that all the properties are now required which is what we want to happen.

See the above code live in [codesandbox](https://codesandbox.io/s/easily-make-every-property-type-or-interface-to-required-typescript-qzjykn?file=/src/index.ts).

That's all 😃!

### Feel free to share if you found this useful 😃.

---
Hey guys! If you're looking to get feedback on your API security, drop a link here 👇 I Would love to help.
Tags: api, security, programming, java
Published: 2022-05-10 23:56:05

Most APIs use Okta, OAuth 2.0, JWT, Spring Security, and similar security frameworks to implement security. These frameworks are hard to implement, and as other developers add new functionality, it gets harder to ensure security is implemented correctly.


I built a free web tool for developers to test their public/mobile/web APIs for authentication flaws. The tool doesn't require access to live traffic. Neither does it need you to write and configure anything. It automatically creates and runs tests against your production/dev APIs and sends a PDF security test report instantly.

The tool I'm going to use:
https://apisec-inc.github.io/pentest/

I need an OpenAPI Specification (Swagger) URL. Leave it in the comments section. I'll get back to you with a PDF report.
Unable to start Netty in spring boot 2.5.13
Published: 2022-05-10 23:43:01

0


I have a spring boot application based on reactor but it can't be launched on Window 10 although it works fine on Linux. It failed to start Netty. This application uses spring boot 2.5.13 now. This issue doesn't exist for the old spring boot 2.3.

The exception was thrown by reactor.core.publisher.BlockingSingleSubscriber.blockingGet.

Is there any config change that could fix this problem? So far, it looks to me like that this problem came from the reactor library and I can't fix by any config change.

Here is the exception stack.

Caused by: org.springframework.boot.web.server.WebServerException: Unable to start Netty at org.springframework.boot.web.embedded.netty.NettyWebServer.start(NettyWebServer.java:108) at org.springframework.boot.web.reactive.context.WebServerManager.start(WebServerManager.java:55) at org.springframework.boot.web.reactive.context.WebServerStartStopLifecycle.start(WebServerStartStopLifecycle.java:40) at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ... 14 common frames omitted Caused by: reactor.core.Exceptions$ReactiveException: java.lang.InterruptedException at reactor.core.Exceptions.propagate(Exceptions.java:392) at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:128) at reactor.core.publisher.Mono.block(Mono.java:1731) at reactor.netty.transport.ServerTransport.bindNow(ServerTransport.java:145) at reactor.netty.transport.ServerTransport.bindNow(ServerTransport.java:130) at org.springframework.boot.web.embedded.netty.NettyWebServer.startHttpServer(NettyWebServer.java:145) at org.springframework.boot.web.embedded.netty.NettyWebServer.start(NettyWebServer.java:100) ... 17 common frames omitted Suppressed: java.lang.Exception: #block has been interrupted at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:130) ... 22 common frames omitted Caused by: java.lang.InterruptedException: null at java.base/java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1367) at java.base/java.util.concurrent.CountDownLatch.await(CountDownLatch.java:278) at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:121) ... 22 common frames omitted
Automatizando o Readme do GitHub
Tags: braziliandevs, automation
Published: 2022-05-10 22:33:45

## Today I Learned 10/05/2022

O GitHub a um tempo atrás lançou uma feature muito interessante que é basicamente readme do seu profile, se você criar um repositório com o mesmo nome que o seu usuário no GitHub e dentro desse repositório criar um README.md, ele aparece assim que o seu perfil é aberto. ![Print do meu perfil](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3a8tmrfgkwjc8ynk8ym0.png)
 
Isso é muito legal para falar um pouco mais sobre você e o que anda pensando, mas para além disso ele pode ser combinado com o github actions para fazer algumas coisas muito legais.

Para isso basta adicionarmos uma pasta .github e criarmos os nossos arquivos de actions. Hoje a integração que fiz foi a de adicionar os meus posts mais recentes do Dev.to. fiz isso utilizando a action [Blog Post Workflow](https://github.com/marketplace/actions/blog-post-workflow)

Para reproduzir basta no readme adicionar a seguinte sessão

```md
# Blog posts
<!-- BLOG-POST-LIST:START -->
<!-- BLOG-POST-LIST:END -->
```

e na pasta .github criar um arquivo com o nome `blog-post-worflow.yml` e copiar o seguinte código

```md
name: Latest blog post workflow
on:
  schedule: # Run workflow automatically
    - cron: '0 0 * * *' # Runs every day
  workflow_dispatch: # Run workflow manually (without waiting for the cron to be called), through the Github Actions Workflow page directly

jobs:
  update-readme-with-blog:
    name: Update this repo's README with latest blog posts
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Pull in dev.to posts
        uses: gautamkrishnar/blog-post-workflow@master
        with:
          feed_list: "https://dev.to/feed/yanpiing"
```

onde no feed_list você muda para o seu nome de usuário no dev.to ou para qualquer feed de blog que você possua, esse job vai rodar diariamente atualizando os posts
Timer Application for Multiple Events by using Appwrite as Backend
Tags: appwritehack
Published: 2022-05-10 22:26:10

### Overview of My Submission

Over time, the timer feature has become essential to many applications, this project will acts as a startup template for those applications.

This project only has one page and it is the timer page. User can add and delete timer for their events.


### Submission Category: 

Web2 Wizards


### Link to Code

{% embed https://github.com/phonist/close_count.git %}
How to get user IP address, location, and device info using JavaScript in browser
Tags: javascript, webdev, react, node
Published: 2022-05-10 22:16:17

JavaScript is not able to get user IP address when running in browser. However, it is possible to do that with a server-side API call. With an API service called [VisitorAPI](https://www.visitorapi.com), you can make it happen in just a couple lines of JavaScript.

VisitorAPI returns the user's IP address, location, currencies, languages, and device info with a REST API call. The following code loads the API:
```
var VisitorAPI=function(t,e,a){var s=new XMLHttpRequest;s.onreadystatechange=function(){var t;s.readyState===XMLHttpRequest.DONE&&(200===(t=JSON.parse(s.responseText)).status?e(t.data):a(t.status,t.result))},s.open("GET","https://visitorapi-dev.uc.r.appspot.com/api/?pid="+t),s.send(null)};
```
Once the API is loaded, you can make an API call with the following syntax:
```
new VisitorAPI(projectID, successHandler, errorHandler);
```

There are 3 parameters in the API call:

- **projectID**: This is unique identifier of your VisitorAPI project which you can create in [VisitorAPI](https://www.visitorapi.com) UI for free.
- **successHandler**: This is a function that process the visitor data when the API call is successfully. See response data format here.
- **errorHandler**: This is a function that handles the error code and error message when the API call returns an error. The function can have two parameters: error code and error message.

Below is an example to print the user data in browser console:
```
VisitorAPI(
    "om61tWZOjuBBPxTdDlpy",
    function(data){console.log(data)},
    function(errorCode, errorMessage){console.log(errorCode, errorMessage)}
);
```

It will print a JSON object similar to the example below based on the current user's real IP address and device data.
```
{
	"ipAddress":"118.211.184.103",
	"countryCode":"AU",
	"countryName":"Australia",
	"currencies":["AUD"],
	"languages":["eng"],
	"region":"nsw",
	"city":"sydney",
	"cityLatLong":"-33.868820,151.209295",
	"browser":"Chrome Mobile iOS",
	"browserVersion":"100",
	"deviceBrand":"Apple",
	"deviceModel":"iPad",
	"deviceFamily":"iPad",
	"os":"iOS",
	"osVersion":"15"
}
```

It is important to note that [VisitorAPI](https://www.visitorapi.com) doesn't use API key to authenticate your API calls, because any API keys would be exposed to the public and that defeats the purpose of the keys. Instead, it allows you to put in an authorized domain list that are allowed to call the API endpoint from, so that no one else is able to call your API endpoint and use your API quota.